From 68fc1a05fca75d6ec90d6ca98691cb46b1660e79 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Wed, 1 Mar 2023 13:08:55 +0100 Subject: [PATCH 01/90] Increased data process speed #87 --- .../telraam/database/daos/DetectionDAO.java | 8 ++- .../telraam/database/models/Detection.java | 9 +++ .../logic/robustLapper/RobustLapper.java | 67 +++++++------------ 3 files changed, 40 insertions(+), 44 deletions(-) diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index be6e6f9..8ca1395 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -3,7 +3,6 @@ import org.jdbi.v3.sqlobject.config.RegisterBeanMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindBean; -import org.jdbi.v3.sqlobject.customizer.BindBeanList; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlBatch; import org.jdbi.v3.sqlobject.statement.SqlQuery; @@ -55,4 +54,11 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id @SqlQuery("SELECT * FROM detection WHERE id > :id ORDER BY id LIMIT :limit") @RegisterBeanMapper(Detection.class) List getSinceId(@Bind("id") int id, @Bind("limit") int limit); + + @SqlQuery(""" + WITH bso AS (SELECT teamid, newbatonid, timestamp AS current_timestamp, LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp) next_baton_switch FROM batonswitchover) + SELECT baton_id, station_id, rssi, timestamp, teamid FROM detection d LEFT JOIN bso ON d.baton_id = bso.newbatonid AND d.timestamp BETWEEN bso.current_timestamp AND bso.next_baton_switch WHERE rssi > :minRssi + """) + @RegisterBeanMapper(Detection.class) + List getAllWithTeamId(@Bind("minRssi") int minRssi); } diff --git a/src/main/java/telraam/database/models/Detection.java b/src/main/java/telraam/database/models/Detection.java index 410167e..6a7c916 100644 --- a/src/main/java/telraam/database/models/Detection.java +++ b/src/main/java/telraam/database/models/Detection.java @@ -12,6 +12,7 @@ public class Detection { private Integer remoteId; private Timestamp timestamp; private Timestamp timestampIngestion; + private Integer teamId; public Detection() { } @@ -98,4 +99,12 @@ public Timestamp getTimestampIngestion() { public void setTimestampIngestion(Timestamp timestampIngestion) { this.timestampIngestion = timestampIngestion; } + + public Integer getTeamId() { + return teamId; + } + + public void setTeamId(Integer teamId) { + this.teamId = teamId; + } } diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index 6774299..0a9520b 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -13,7 +13,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -import java.util.stream.Collectors; // Implement Lapper for easier use in App and Fetcher public class RobustLapper implements Lapper { @@ -30,7 +29,6 @@ public class RobustLapper implements Lapper { private boolean debounceScheduled; private int lapSourceId; private Map> teamDetections; - private List teams; private List stations; private Map> teamLaps; @@ -49,47 +47,32 @@ public RobustLapper(Jdbi jdbi) { ); } + // Group all detections by time and keep only one detection per timestamp private void processData() { - // Maps a baton id to the current team using it - Map batonTeam = new HashMap<>(); - // Map containing all detections belonging to a team - teamDetections = new HashMap<>(); - - TeamDAO teamDAO = this.jdbi.onDemand(TeamDAO.class); DetectionDAO detectionDAO = this.jdbi.onDemand(DetectionDAO.class); - BatonSwitchoverDAO batonSwitchoverDAO = this.jdbi.onDemand(BatonSwitchoverDAO.class); - - teams = teamDAO.getAll(); - List detections = detectionDAO.getAll(); - List switchovers = batonSwitchoverDAO.getAll(); - - switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); + List detections = detectionDAO.getAllWithTeamId(MIN_RSSI); detections.sort(Comparator.comparing(Detection::getTimestamp)); + teamDetections = new HashMap<>(); - Map teamById = teams.stream().collect(Collectors.toMap(Team::getId, team -> team)); - teams.forEach(team -> teamDetections.put(team.getId(), new ArrayList<>())); - - int switchoverIndex = 0; for (Detection detection : detections) { - // Switch teams batons if it happened before the current detection - while (switchoverIndex < switchovers.size() && switchovers.get(switchoverIndex).getTimestamp().before(detection.getTimestamp())) { - BatonSwitchover switchover = switchovers.get(switchoverIndex); - batonTeam.put(switchover.getNewBatonId(), teamById.get(switchover.getTeamId())); - batonTeam.remove(switchover.getPreviousBatonId()); - switchoverIndex++; - } - - // Check if detection belongs to a team, and it's signal is strong enough - if (batonTeam.containsKey(detection.getBatonId()) && detection.getRssi() > MIN_RSSI) { - List currentDetections = teamDetections.get(batonTeam.get(detection.getBatonId()).getId()); - // If team already has a detection for that timestamp keep the one with the strongest signal - if (! currentDetections.isEmpty() && currentDetections.get(currentDetections.size() - 1).getTimestamp().compareTo(detection.getTimestamp()) == 0) { - if (currentDetections.get(currentDetections.size() - 1).getRssi() < detection.getRssi()) { - currentDetections.remove(currentDetections.size() - 1); - currentDetections.add(detection); + if (detection.getTeamId() != null) { + if (teamDetections.containsKey(detection.getTeamId())) { + // teamDetections already contains teamId + List teamDetectionsList = teamDetections.get(detection.getTeamId()); + if (teamDetectionsList.get(teamDetectionsList.size() - 1).getTimestamp().compareTo(detection.getTimestamp()) == 0) { + // There's already a detection for that timestamp, keep the one with the highest rssi + if (teamDetectionsList.get(teamDetectionsList.size() - 1).getRssi() < detection.getRssi()) { + teamDetectionsList.remove(teamDetectionsList.size() - 1); + teamDetectionsList.add(detection); + } + } else { + // No detection yet for that timestamp so let's add it + teamDetectionsList.add(detection); } } else { - currentDetections.add(detection); + // Team id isn't in teamDetections yet so let's add it + teamDetections.put(detection.getTeamId(), new ArrayList<>()); + teamDetections.get(detection.getTeamId()).add(detection); } } } @@ -108,7 +91,7 @@ public void calculateLaps() { // List containing station id's and sorted based on their distance from the start List stationIdToPosition = stations.stream().map(Station::getId).toList(); - for (Team team : teams) { + for (Map.Entry> entry : teamDetections.entrySet()) { List lapTimes = new ArrayList<>(); // Station that is used for current interval @@ -117,9 +100,7 @@ public void calculateLaps() { int currentStationRssi = MIN_RSSI; int currentStationPosition = 0; - List detections = teamDetections.get(team.getId()); - - for (Detection detection : detections) { + for (Detection detection : entry.getValue()) { // Group all detections based on INTERVAL_TIME if (detection.getTimestamp().getTime() - currentStationTime < INTERVAL_TIME) { // We're still in the same interval @@ -146,7 +127,7 @@ public void calculateLaps() { } } // Save result for team - teamLaps.put(team.getId(), lapTimes); + teamLaps.put(entry.getKey(), lapTimes); } save(); @@ -158,13 +139,13 @@ private int backwardPathDistance(int fromStation, int toStation) { return (((fromStation - toStation) % stations.size()) + stations.size()) % stations.size(); } - // Is the finish line between from_station and to_station when running forwards? + // Returns whether the finish line is between from_station and to_station when running forwards private boolean isStartBetween(int fromStation, int toStation) { return fromStation > toStation; } private void save() { - lapDAO.deleteByLapSourceId(this.lapSourceId); + lapDAO.deleteByLapSourceId(lapSourceId); LinkedList laps = new LinkedList<>(); for (Map.Entry> entries : teamLaps.entrySet()) { From e76ac0c5dc0e8825cff37953d7e54d8245dda332 Mon Sep 17 00:00:00 2001 From: topvennie Date: Thu, 2 Mar 2023 17:54:00 +0100 Subject: [PATCH 02/90] Only add new laps --- .../java/telraam/database/daos/LapDAO.java | 5 ++++- .../logic/robustLapper/RobustLapper.java | 20 +++++++++++++------ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index 9dc47bb..f81fb76 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -3,7 +3,6 @@ import org.jdbi.v3.sqlobject.config.RegisterBeanMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindBean; -import org.jdbi.v3.sqlobject.customizer.BindBeanList; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlBatch; import org.jdbi.v3.sqlobject.statement.SqlQuery; @@ -50,4 +49,8 @@ public interface LapDAO extends DAO { @SqlBatch("INSERT INTO lap (team_id, lap_source_id, timestamp) VALUES (:teamId, :lapSourceId, :timestamp)") void insertAll(@BindBean Iterator laps); + + @SqlQuery("DELETE FROM lap WHERE id in (SELECT id FROM lap WHERE team_id = :teamId AND lap_source_id = :lapSourceId ORDER BY timestamp DESC LIMIT 2) RETURNING *") + @RegisterBeanMapper(Lap.class) + List deleteLatestTwoLaps(@Bind("teamId") int teamId, @Bind("lapSourceId") int lapSourceId); } diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index 0a9520b..d62c998 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -5,7 +5,6 @@ import telraam.database.daos.*; import telraam.database.models.*; import telraam.logic.Lapper; -import telraam.logic.viterbi.ViterbiLapper; import java.sql.Timestamp; import java.util.*; @@ -35,7 +34,7 @@ public class RobustLapper implements Lapper { public RobustLapper(Jdbi jdbi) { this.jdbi = jdbi; this.scheduler = Executors.newScheduledThreadPool(1); - this.logger = Logger.getLogger(ViterbiLapper.class.getName()); + this.logger = Logger.getLogger(RobustLapper.class.getName()); this.lapDAO = jdbi.onDemand(LapDAO.class); this.debounceScheduled = false; @@ -145,13 +144,22 @@ private boolean isStartBetween(int fromStation, int toStation) { } private void save() { - lapDAO.deleteByLapSourceId(lapSourceId); - LinkedList laps = new LinkedList<>(); + for (Map.Entry> entries : teamLaps.entrySet()) { - for (Timestamp timestamp : entries.getValue()) { - laps.add(new Lap(entries.getKey(), lapSourceId, timestamp)); + // Delete last two laps + List deletedLaps = lapDAO.deleteLatestTwoLaps(entries.getKey(), lapSourceId); + Timestamp minTimestamp; + if (deletedLaps.size() == 2) { + deletedLaps.sort(Comparator.comparing(Lap::getTimestamp)); + minTimestamp = deletedLaps.get(0).getTimestamp(); + } else { + minTimestamp = new Timestamp(0); } + // Only add new laps + entries.getValue().stream() + .filter(timestamp -> timestamp.getTime() >= minTimestamp.getTime()) + .forEach(timestamp -> laps.add(new Lap(entries.getKey(), lapSourceId, timestamp))); } lapDAO.insertAll(laps.iterator()); From c7831c09792629335de3324132ff0cc36550f460 Mon Sep 17 00:00:00 2001 From: FKD13 Date: Mon, 6 Mar 2023 01:40:43 +0100 Subject: [PATCH 03/90] only make the required changes to the laps in the database --- .../java/telraam/database/daos/LapDAO.java | 4 +- .../logic/external/ExternalLapper.java | 42 ++++++++++++++++--- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index 9dc47bb..c2bfbe5 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -3,7 +3,6 @@ import org.jdbi.v3.sqlobject.config.RegisterBeanMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindBean; -import org.jdbi.v3.sqlobject.customizer.BindBeanList; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlBatch; import org.jdbi.v3.sqlobject.statement.SqlQuery; @@ -48,6 +47,9 @@ public interface LapDAO extends DAO { @SqlUpdate("DELETE FROM lap WHERE lap_source_id = :lapSourceId") void deleteByLapSourceId(@Bind("lapSourceId") int lapSourceId); + @SqlBatch("DELETE FROM lap WHERE id = :id") + void deleteAllById(@BindBean Iterator laps); + @SqlBatch("INSERT INTO lap (team_id, lap_source_id, timestamp) VALUES (:teamId, :lapSourceId, :timestamp)") void insertAll(@BindBean Iterator laps); } diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index f82d55d..4a64a7d 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -9,7 +9,9 @@ import telraam.database.models.LapSource; import telraam.logic.Lapper; +import javax.ws.rs.core.Link; import java.sql.Timestamp; +import java.util.Comparator; import java.util.LinkedList; import java.util.List; @@ -36,18 +38,46 @@ public void handle(Detection msg) { } public void saveLaps(List teamLaps) { - //TODO: Be less destructive on the database: Only delete and add the required laps. - lapDAO.deleteByLapSourceId(this.lapSourceId); + List laps = lapDAO.getAllBySource(lapSourceId); - LinkedList laps = new LinkedList<>(); + // Remember laps we have to take actions on + List lapsToDelete = new LinkedList<>(); + List lapsToAdd = new LinkedList<>(); + // Find which laps are no longer needed or have to be added for (ExternalLapperTeamLaps teamLap : teamLaps) { - for (ExternalLapperLap lap : teamLap.laps) { - laps.add(new Lap(teamLap.teamId, this.lapSourceId, new Timestamp((long) (lap.timestamp)))); + List lapsForTeam = laps.stream().filter(l -> l.getTeamId() == teamLap.teamId).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); + List newLapsForTeam = teamLap.laps.stream().map(nl -> new Lap(teamLap.teamId, lapSourceId, new Timestamp((long) (nl.timestamp)))).sorted(Comparator.comparing(Lap::getTimestamp)).toList();; + + int lapsIndex = 0; + int newLapsIndex = 0; + while (lapsIndex != lapsForTeam.size() || newLapsIndex != newLapsForTeam.size()) { + if (lapsIndex != lapsForTeam.size() && newLapsIndex != newLapsForTeam.size()) { + Lap lap = lapsForTeam.get(lapsIndex); + Lap newLap = newLapsForTeam.get(newLapsIndex); + if (lap.getTimestamp().before(newLap.getTimestamp())) { + lapsToDelete.add(lap); + lapsIndex++; + } else if (lap.getTimestamp().after(newLap.getTimestamp())) { + lapsToAdd.add(newLap); + newLapsIndex++; + } else { // Lap is present in both lists. Keep it. + lapsIndex++; + newLapsIndex++; + } + } else if (lapsIndex != lapsForTeam.size()) { + lapsToDelete.add(lapsForTeam.get(lapsIndex)); + lapsIndex++; + } else { + lapsToAdd.add(newLapsForTeam.get(newLapsIndex)); + newLapsIndex++; + } } } - lapDAO.insertAll(laps.iterator()); + // Do the required actions + lapDAO.deleteAllById(lapsToDelete.iterator()); + lapDAO.insertAll(lapsToAdd.iterator()); } @Override From badeb25c2da2b39ab14f8fd32fc0d14ee26c86be Mon Sep 17 00:00:00 2001 From: topvennie Date: Mon, 6 Mar 2023 23:40:07 +0100 Subject: [PATCH 04/90] Better way of saving new laps --- .../java/telraam/database/daos/LapDAO.java | 8 ++- .../logic/robustLapper/RobustLapper.java | 69 ++++++++++++++----- 2 files changed, 56 insertions(+), 21 deletions(-) diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index f81fb76..90bed6f 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -50,7 +50,9 @@ public interface LapDAO extends DAO { @SqlBatch("INSERT INTO lap (team_id, lap_source_id, timestamp) VALUES (:teamId, :lapSourceId, :timestamp)") void insertAll(@BindBean Iterator laps); - @SqlQuery("DELETE FROM lap WHERE id in (SELECT id FROM lap WHERE team_id = :teamId AND lap_source_id = :lapSourceId ORDER BY timestamp DESC LIMIT 2) RETURNING *") - @RegisterBeanMapper(Lap.class) - List deleteLatestTwoLaps(@Bind("teamId") int teamId, @Bind("lapSourceId") int lapSourceId); + @SqlBatch("UPDATE lap SET timestamp = :timestamp WHERE id = :id") + void updateAll(@BindBean Iterator laps); + + @SqlBatch("DELETE FROM lap WHERE id = :id") + void deleteAll(@BindBean Iterator laps); } diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index d62c998..c829515 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -12,6 +12,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; +import java.util.stream.Collectors; // Implement Lapper for easier use in App and Fetcher public class RobustLapper implements Lapper { @@ -29,7 +30,7 @@ public class RobustLapper implements Lapper { private int lapSourceId; private Map> teamDetections; private List stations; - private Map> teamLaps; + private Map> teamLaps; public RobustLapper(Jdbi jdbi) { this.jdbi = jdbi; @@ -126,7 +127,7 @@ public void calculateLaps() { } } // Save result for team - teamLaps.put(entry.getKey(), lapTimes); + teamLaps.put(entry.getKey(), lapTimes.stream().map(time -> new Lap(entry.getKey(), lapSourceId, time)).collect(Collectors.toList())); } save(); @@ -144,25 +145,57 @@ private boolean isStartBetween(int fromStation, int toStation) { } private void save() { - LinkedList laps = new LinkedList<>(); - - for (Map.Entry> entries : teamLaps.entrySet()) { - // Delete last two laps - List deletedLaps = lapDAO.deleteLatestTwoLaps(entries.getKey(), lapSourceId); - Timestamp minTimestamp; - if (deletedLaps.size() == 2) { - deletedLaps.sort(Comparator.comparing(Lap::getTimestamp)); - minTimestamp = deletedLaps.get(0).getTimestamp(); - } else { - minTimestamp = new Timestamp(0); + // Get all the old laps and sort by team + List laps = lapDAO.getAllBySource(lapSourceId); + Map> oldLaps = new HashMap<>(); + + for (Integer teamId : teamLaps.keySet()) { + oldLaps.put(teamId, new ArrayList<>()); + } + + for (Lap lap : laps) { + oldLaps.get(lap.getTeamId()).add(lap); + } + + List lapsToUpdate = new ArrayList<>(); + List lapsToInsert = new ArrayList<>(); + List lapsToDelete = new ArrayList<>(); + + for (Map.Entry> entries : teamLaps.entrySet()) { + List newLapsTeam = entries.getValue(); + List oldLapsTeam = oldLaps.get(entries.getKey()); + oldLapsTeam.sort(Comparator.comparing(Lap::getTimestamp)); + int i = 0; + // Go over each lap and compare timestamp + while (i < oldLapsTeam.size() && i < newLapsTeam.size()) { + // Update the timestamp if it isn't equal + if (! oldLapsTeam.get(i).getTimestamp().equals(newLapsTeam.get(i).getTimestamp())) { + oldLapsTeam.get(i).setTimestamp(newLapsTeam.get(i).getTimestamp()); + lapsToUpdate.add(oldLapsTeam.get(i)); + } + i++; + } + + // More old laps so delete the surplus + if (i < oldLapsTeam.size()) { + while (i < oldLapsTeam.size()) { + lapsToDelete.add(oldLapsTeam.get(i)); + i++; + } + } + + // Add the new laps + if (i < newLapsTeam.size()) { + while (i < newLapsTeam.size()) { + lapsToInsert.add(newLapsTeam.get(i)); + i++; + } } - // Only add new laps - entries.getValue().stream() - .filter(timestamp -> timestamp.getTime() >= minTimestamp.getTime()) - .forEach(timestamp -> laps.add(new Lap(entries.getKey(), lapSourceId, timestamp))); } - lapDAO.insertAll(laps.iterator()); + lapDAO.updateAll(lapsToUpdate.iterator()); + lapDAO.insertAll(lapsToInsert.iterator()); + lapDAO.deleteAll(lapsToDelete.iterator()); } @Override From 0866e9a6cd970f328fe22a923e0f3c5873186c45 Mon Sep 17 00:00:00 2001 From: topvennie Date: Mon, 6 Mar 2023 23:46:29 +0100 Subject: [PATCH 05/90] Small cleanup --- .../telraam/logic/robustLapper/RobustLapper.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index c829515..9c0e778 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -177,19 +177,15 @@ private void save() { } // More old laps so delete the surplus - if (i < oldLapsTeam.size()) { - while (i < oldLapsTeam.size()) { - lapsToDelete.add(oldLapsTeam.get(i)); - i++; - } + while (i < oldLapsTeam.size()) { + lapsToDelete.add(oldLapsTeam.get(i)); + i++; } // Add the new laps - if (i < newLapsTeam.size()) { - while (i < newLapsTeam.size()) { - lapsToInsert.add(newLapsTeam.get(i)); - i++; - } + while (i < newLapsTeam.size()) { + lapsToInsert.add(newLapsTeam.get(i)); + i++; } } From 1d0791c765417cb697f5025381b6119e4ee56025 Mon Sep 17 00:00:00 2001 From: topvennie Date: Mon, 6 Mar 2023 23:54:36 +0100 Subject: [PATCH 06/90] ignore manual laps --- src/main/java/telraam/database/models/Lap.java | 9 +++++++++ .../java/telraam/logic/robustLapper/RobustLapper.java | 1 + 2 files changed, 10 insertions(+) diff --git a/src/main/java/telraam/database/models/Lap.java b/src/main/java/telraam/database/models/Lap.java index cf45139..f084c9c 100644 --- a/src/main/java/telraam/database/models/Lap.java +++ b/src/main/java/telraam/database/models/Lap.java @@ -6,6 +6,7 @@ public class Lap { private Integer id; private Integer teamId; private Integer lapSourceId; + private Boolean manual; private Timestamp timestamp; @@ -42,6 +43,14 @@ public void setLapSourceId(Integer lapSourceId) { this.lapSourceId = lapSourceId; } + public Boolean getManual() { + return manual; + } + + public void setManual(Boolean manual) { + this.manual = manual; + } + public Timestamp getTimestamp() { return timestamp; } diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index 9c0e778..3cea4cf 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -147,6 +147,7 @@ private boolean isStartBetween(int fromStation, int toStation) { private void save() { // Get all the old laps and sort by team List laps = lapDAO.getAllBySource(lapSourceId); + laps = laps.stream().filter(lap -> ! lap.getManual()).collect(Collectors.toList()); Map> oldLaps = new HashMap<>(); for (Integer teamId : teamLaps.keySet()) { From 18d0f556499910b2f059eb0427a0266567ab1733 Mon Sep 17 00:00:00 2001 From: topvennie Date: Tue, 7 Mar 2023 21:38:48 +0100 Subject: [PATCH 07/90] Code smells --- src/main/java/telraam/logic/robustLapper/RobustLapper.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index 3cea4cf..bb3e974 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -12,7 +12,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -import java.util.stream.Collectors; // Implement Lapper for easier use in App and Fetcher public class RobustLapper implements Lapper { @@ -127,7 +126,7 @@ public void calculateLaps() { } } // Save result for team - teamLaps.put(entry.getKey(), lapTimes.stream().map(time -> new Lap(entry.getKey(), lapSourceId, time)).collect(Collectors.toList())); + teamLaps.put(entry.getKey(), lapTimes.stream().map(time -> new Lap(entry.getKey(), lapSourceId, time)).toList()); } save(); @@ -147,7 +146,7 @@ private boolean isStartBetween(int fromStation, int toStation) { private void save() { // Get all the old laps and sort by team List laps = lapDAO.getAllBySource(lapSourceId); - laps = laps.stream().filter(lap -> ! lap.getManual()).collect(Collectors.toList()); + laps = laps.stream().filter(lap -> ! lap.getManual()).toList(); Map> oldLaps = new HashMap<>(); for (Integer teamId : teamLaps.keySet()) { From 98628df41a44f2fcd595c91d655ecaff3ef727ac Mon Sep 17 00:00:00 2001 From: Francis Date: Wed, 8 Mar 2023 00:06:04 +0100 Subject: [PATCH 08/90] add endpoints for publishing external lapper stats --- .../logic/external/ExternalLapper.java | 3 +- .../external/ExternalLapperResource.java | 31 ++++++++++--------- .../logic/external/ExternalLapperStats.java | 29 +++++++++++++++++ 3 files changed, 47 insertions(+), 16 deletions(-) diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index 4a64a7d..d3de736 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -9,7 +9,6 @@ import telraam.database.models.LapSource; import telraam.logic.Lapper; -import javax.ws.rs.core.Link; import java.sql.Timestamp; import java.util.Comparator; import java.util.LinkedList; @@ -47,7 +46,7 @@ public void saveLaps(List teamLaps) { // Find which laps are no longer needed or have to be added for (ExternalLapperTeamLaps teamLap : teamLaps) { List lapsForTeam = laps.stream().filter(l -> l.getTeamId() == teamLap.teamId).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); - List newLapsForTeam = teamLap.laps.stream().map(nl -> new Lap(teamLap.teamId, lapSourceId, new Timestamp((long) (nl.timestamp)))).sorted(Comparator.comparing(Lap::getTimestamp)).toList();; + List newLapsForTeam = teamLap.laps.stream().map(nl -> new Lap(teamLap.teamId, lapSourceId, new Timestamp((long) (nl.timestamp)))).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); int lapsIndex = 0; int newLapsIndex = 0; diff --git a/src/main/java/telraam/logic/external/ExternalLapperResource.java b/src/main/java/telraam/logic/external/ExternalLapperResource.java index add3ceb..07d9ef5 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperResource.java +++ b/src/main/java/telraam/logic/external/ExternalLapperResource.java @@ -3,6 +3,7 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; @@ -16,8 +17,11 @@ public class ExternalLapperResource { private final ExternalLapper lapper; + private ExternalLapperStats externalLapperStats; + public ExternalLapperResource(ExternalLapper lapper) { this.lapper = lapper; + this.externalLapperStats = new ExternalLapperStats(); } @POST @@ -27,19 +31,18 @@ public void postLaps(List teamLaps) { this.lapper.saveLaps(teamLaps); } - //TODO: Give the lapper an option to publish some of its internal state for debugging. - //@GET - //@Path("/stats") - //@ApiOperation(value = "Get lapper statistics") - //public Map> getStats() { - // //return this.lapper.getLapCounts(); - //} -// - //@POST - //@Path("/stats") - //@ApiOperation(value = "Post lapper statistics") - //public Map> postStats() { - // return this.lapper.getLapCounts(); - //} + @GET + @Path("/stats") + @ApiOperation(value = "Get lapper statistics") + public ExternalLapperStats getStats() { + return externalLapperStats; + } + + @POST + @Path("/stats") + @ApiOperation(value = "Post lapper statistics") + public void postStats(ExternalLapperStats externalLapperStats) { + this.externalLapperStats = externalLapperStats; + } } diff --git a/src/main/java/telraam/logic/external/ExternalLapperStats.java b/src/main/java/telraam/logic/external/ExternalLapperStats.java index c285729..9910898 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperStats.java +++ b/src/main/java/telraam/logic/external/ExternalLapperStats.java @@ -1,4 +1,33 @@ package telraam.logic.external; +import java.util.List; + public class ExternalLapperStats { + private List errorHistory; + private List> transitionMatrix; + private List> emissionMatrix; + + public List getErrorHistory() { + return errorHistory; + } + + public void setErrorHistory(List errorHistory) { + this.errorHistory = errorHistory; + } + + public List> getTransitionMatrix() { + return transitionMatrix; + } + + public void setTransitionMatrix(List> transitionMatrix) { + this.transitionMatrix = transitionMatrix; + } + + public List> getEmissionMatrix() { + return emissionMatrix; + } + + public void setEmissionMatrix(List> emissionMatrix) { + this.emissionMatrix = emissionMatrix; + } } From 2a690d3dea9f6ed133cf32014d0bdcb4a40b5b43 Mon Sep 17 00:00:00 2001 From: Francis Date: Wed, 8 Mar 2023 00:15:36 +0100 Subject: [PATCH 09/90] only process laps that are not manual --- src/main/java/telraam/logic/external/ExternalLapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index d3de736..cd1158b 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -37,7 +37,7 @@ public void handle(Detection msg) { } public void saveLaps(List teamLaps) { - List laps = lapDAO.getAllBySource(lapSourceId); + List laps = lapDAO.getAllBySource(lapSourceId).stream().filter(l -> ! l.getManual()).toList(); // Remember laps we have to take actions on List lapsToDelete = new LinkedList<>(); From 3a9a9d84ed3b9ba96bdfcdd3c225f105ced4d481 Mon Sep 17 00:00:00 2001 From: redfast00 <10746993+redfast00@users.noreply.github.com> Date: Wed, 8 Mar 2023 13:11:39 +0100 Subject: [PATCH 10/90] Add metric endpoints (#98) Co-authored-by: NuttyShrimp --- src/main/java/telraam/App.java | 2 +- .../java/telraam/api/MonitoringResource.java | 115 +++++++++++++++++ .../telraam/database/daos/DetectionDAO.java | 6 + .../java/telraam/database/daos/LapDAO.java | 10 ++ .../telraam/database/models/TeamLapCount.java | 32 +++++ .../monitoring/BatonDetectionManager.java | 47 +++++++ .../telraam/monitoring/BatonStatusHolder.java | 121 ++++++++++++++++++ .../monitoring/models/BatonDetection.java | 45 +++++++ .../monitoring/models/BatonStatus.java | 113 ++++++++++++++++ .../monitoring/models/LapCountForTeam.java | 17 +++ .../monitoring/models/TeamLapInfo.java | 21 +++ 11 files changed, 528 insertions(+), 1 deletion(-) create mode 100644 src/main/java/telraam/api/MonitoringResource.java create mode 100644 src/main/java/telraam/database/models/TeamLapCount.java create mode 100644 src/main/java/telraam/monitoring/BatonDetectionManager.java create mode 100644 src/main/java/telraam/monitoring/BatonStatusHolder.java create mode 100644 src/main/java/telraam/monitoring/models/BatonDetection.java create mode 100644 src/main/java/telraam/monitoring/models/BatonStatus.java create mode 100644 src/main/java/telraam/monitoring/models/LapCountForTeam.java create mode 100644 src/main/java/telraam/monitoring/models/TeamLapInfo.java diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 6f02ab9..a4ba783 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -17,7 +17,6 @@ import telraam.logic.Lapper; import telraam.logic.external.ExternalLapper; import telraam.logic.robustLapper.RobustLapper; -import telraam.logic.viterbi.ViterbiLapper; import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; @@ -92,6 +91,7 @@ public void run(AppConfiguration configuration, Environment environment) throws jersey.register(new AcceptedLapsResource()); jersey.register(new TimeResource()); jersey.register(new LapCountResource(database.onDemand(TeamDAO.class))); + jersey.register(new MonitoringResource(database)); environment.healthChecks().register("template", new TemplateHealthCheck(configuration.getTemplate())); diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java new file mode 100644 index 0000000..c9810e1 --- /dev/null +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -0,0 +1,115 @@ +package telraam.api; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.*; +import telraam.database.models.Lap; +import telraam.database.models.LapSource; +import telraam.database.models.Team; +import telraam.database.models.TeamLapCount; +import telraam.monitoring.*; +import telraam.monitoring.models.BatonDetection; +import telraam.monitoring.models.BatonStatus; +import telraam.monitoring.models.LapCountForTeam; +import telraam.monitoring.models.TeamLapInfo; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.*; + +@Path("/monitoring") +@Api("/monitoring") +@Produces(MediaType.APPLICATION_JSON) +public class MonitoringResource { + private final BatonStatusHolder batonStatusHolder; + private final BatonDetectionManager batonDetectionManager; + private final TeamDAO teamDAO; + private final LapDAO lapDAO; + private final LapSourceDAO lapSourceDAO; + + public MonitoringResource(Jdbi jdbi) { + this.teamDAO = jdbi.onDemand(TeamDAO.class); + this.lapDAO = jdbi.onDemand(LapDAO.class); + this.lapSourceDAO = jdbi.onDemand(LapSourceDAO.class); + this.batonStatusHolder = new BatonStatusHolder(jdbi.onDemand(BatonDAO.class), jdbi.onDemand(DetectionDAO.class)); + this.batonDetectionManager = new BatonDetectionManager(jdbi.onDemand(DetectionDAO.class), this.teamDAO); + } + + @GET + @Path("/batons") + @ApiOperation(value = "Get the status of all the batons, including unused batons which are toggleable via a parameter") + public List getBatonMetrics(@QueryParam("filter_assigned") boolean filterAssigned) { + List batonStatuses = batonStatusHolder.GetAllBatonStatuses(); + if (filterAssigned) { + List teams = teamDAO.getAll(); + Set usedBatonIds = new HashSet<>(); + for (Team team : teams) { + usedBatonIds.add(team.getBatonId()); + } + return batonStatuses.stream().filter(batonStatus -> usedBatonIds.contains(batonStatus.getId())).toList(); + } + return batonStatuses; + } + + @POST + @Path("/reset-rebooted/{batonId}") + @ApiOperation(value = "Reset the rebooted flag of a baton") + public void resetRebooted(@PathParam("batonId") Integer batonId) { + batonStatusHolder.resetRebooted(batonId); + } + + @GET + @Path("/team-detection-times") + @ApiOperation(value = "A map of all detections per batons") + public Map> getTeamDetectionTimes() { + return batonDetectionManager.getBatonDetections(); + } + + @GET + @Path("/team-lap-times/{lapperId}") + @ApiOperation(value = "Get monitoring data that can be used as grafana datasource") + public Map> getTeamLapTimes(@PathParam("lapperId") Integer id) { + List laps = lapDAO.getAllBySourceSorted(id); + List teams = teamDAO.getAll(); + Map teamMap = new HashMap<>(); + for (Team team : teams) { + teamMap.put(team.getId(), team); + } + Map> teamLapInfos = new HashMap<>(); + Map previousLap = new HashMap<>(); + for (Lap lap : laps) { + if (!previousLap.containsKey(lap.getTeamId())) { + previousLap.put(lap.getTeamId(), lap); + continue; + } + Lap prevLap = previousLap.get(lap.getTeamId()); + previousLap.put(lap.getTeamId(), lap); + if (!teamLapInfos.containsKey(lap.getTeamId())) { + teamLapInfos.put(lap.getTeamId(), new ArrayList<>()); + } + Team team = teamMap.get(lap.getTeamId()); + teamLapInfos.get(lap.getTeamId()).add(new TeamLapInfo((lap.getTimestamp().getTime() - prevLap.getTimestamp().getTime()) / 1000, lap.getTimestamp().getTime() / 1000, lap.getTeamId(), team.getName())); + } + return teamLapInfos; + } + + @GET + @Path("/team-lap-counts") + @ApiOperation(value = "Get monitoring data that can be used as grafana datasource") + public List getTeamLapCounts() { + List teams = teamDAO.getAll(); + List lapSources = lapSourceDAO.getAll(); + List lapCountForTeams = new ArrayList<>(); + for (Team team : teams) { + var teamLapsCount = lapDAO.getAllBySourceAndTeam(team.getId()); + Map lapCounts = new HashMap<>(); + lapSources.forEach(lapSource -> lapCounts.put(lapSource.getId(), 0)); + for (TeamLapCount teamLapCount : teamLapsCount) { + lapCounts.put(teamLapCount.getLapSourceId(), teamLapCount.getLapCount()); + } + lapCountForTeams.add(new LapCountForTeam(team.getName(), lapCounts)); + } + return lapCountForTeams; + } +} diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index 8ca1395..baefc4a 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -9,6 +9,7 @@ import org.jdbi.v3.sqlobject.statement.SqlUpdate; import telraam.database.models.Detection; +import java.sql.Timestamp; import java.util.List; import java.util.Optional; @@ -55,6 +56,11 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id @RegisterBeanMapper(Detection.class) List getSinceId(@Bind("id") int id, @Bind("limit") int limit); + + @SqlQuery("SELECT * FROM detection WHERE baton_id = :batonId AND timestamp > :timestamp ORDER BY timestamp DESC LIMIT 1") + @RegisterBeanMapper(Detection.class) + Optional latestDetectionByBatonId(@Bind("batonId") int batonId, @Bind("timestamp") Timestamp timestamp); + @SqlQuery(""" WITH bso AS (SELECT teamid, newbatonid, timestamp AS current_timestamp, LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp) next_baton_switch FROM batonswitchover) SELECT baton_id, station_id, rssi, timestamp, teamid FROM detection d LEFT JOIN bso ON d.baton_id = bso.newbatonid AND d.timestamp BETWEEN bso.current_timestamp AND bso.next_baton_switch WHERE rssi > :minRssi diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index 6e2124b..8c98785 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -8,11 +8,13 @@ import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import telraam.database.models.Lap; +import telraam.database.models.TeamLapCount; import java.sql.Timestamp; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Optional; public interface LapDAO extends DAO { @@ -25,6 +27,10 @@ public interface LapDAO extends DAO { @RegisterBeanMapper(Lap.class) List getAllBySource(@Bind("lapSourceId") Integer lapSourceId); + @SqlQuery("SELECT * FROM lap WHERE lap_source_id = :lapSourceId ORDER BY timestamp ASC") + @RegisterBeanMapper(Lap.class) + List getAllBySourceSorted(@Bind("lapSourceId") Integer lapSourceId); + @SqlUpdate("INSERT INTO lap (team_id, lap_source_id, timestamp) " + "VALUES (:teamId, :lapSourceId, :timestamp)") @GetGeneratedKeys({"id"}) @@ -64,4 +70,8 @@ public interface LapDAO extends DAO { @SqlBatch("DELETE FROM lap WHERE id = :id") void deleteAll(@BindBean Iterator laps); + + @SqlQuery("SELECT COUNT(*) as lapCount, lap_source_id FROM lap WHERE team_id = :teamId GROUP BY lap_source_id") + @RegisterBeanMapper(TeamLapCount.class) + List getAllBySourceAndTeam(@Bind("teamId") int teamId); } diff --git a/src/main/java/telraam/database/models/TeamLapCount.java b/src/main/java/telraam/database/models/TeamLapCount.java new file mode 100644 index 0000000..96699a9 --- /dev/null +++ b/src/main/java/telraam/database/models/TeamLapCount.java @@ -0,0 +1,32 @@ +package telraam.database.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class TeamLapCount { + private Integer lapSourceId; + private Integer lapCount; + + public TeamLapCount() { + } + + public TeamLapCount(Integer lapTeamId, Integer lapCount) { + this.lapSourceId = lapTeamId; + this.lapCount = lapCount; + } + + public Integer getLapSourceId() { + return lapSourceId; + } + + public void setLapSourceId(Integer lapSourceId) { + this.lapSourceId = lapSourceId; + } + + public Integer getLapCount() { + return lapCount; + } + + public void setLapCount(Integer lapCount) { + this.lapCount = lapCount; + } +} diff --git a/src/main/java/telraam/monitoring/BatonDetectionManager.java b/src/main/java/telraam/monitoring/BatonDetectionManager.java new file mode 100644 index 0000000..ec35308 --- /dev/null +++ b/src/main/java/telraam/monitoring/BatonDetectionManager.java @@ -0,0 +1,47 @@ +package telraam.monitoring; + +import telraam.database.daos.DetectionDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.Team; +import telraam.monitoring.models.BatonDetection; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BatonDetectionManager { + private DetectionDAO detectionDAO; + private TeamDAO teamDAO; + + // Map of a baton id to it's detections + private Map> batonDetectionMap = new HashMap<>(); + private Integer handledDetectionId = 0; + + public BatonDetectionManager(DetectionDAO detectionDAO, TeamDAO teamDAO) { + this.detectionDAO = detectionDAO; + this.teamDAO = teamDAO; + } + + public Map> getBatonDetections() { + var detections = detectionDAO.getSinceId(handledDetectionId, Integer.MAX_VALUE); + // Map of batonIds to team info + var teamMap = new HashMap(); + var teams = teamDAO.getAll(); + teams.forEach(t -> teamMap.put(t.getBatonId(), t)); + detections.forEach(d -> { + if (d.getId() > handledDetectionId) { + handledDetectionId = d.getId(); + } + Integer batonId = d.getBatonId(); + if (!batonDetectionMap.containsKey(batonId)) { + batonDetectionMap.put(batonId, new ArrayList<>()); + } + var batonDetections = batonDetectionMap.get(batonId); + var team = teamMap.get(batonId); + var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), batonId, team.getName()); + batonDetections.add(batonDetection); + }); + return batonDetectionMap; + } +} diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java new file mode 100644 index 0000000..db59421 --- /dev/null +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -0,0 +1,121 @@ +package telraam.monitoring; + +import telraam.database.daos.BatonDAO; +import telraam.database.daos.DetectionDAO; +import telraam.database.models.Baton; +import telraam.database.models.Detection; +import telraam.monitoring.models.BatonStatus; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class BatonStatusHolder { + // Map from batonMac to batonStatus + private HashMap batonStatusMap = new HashMap<>(); + private HashMap batonIdToMac = new HashMap<>(); + + private BatonDAO batonDAO; + private DetectionDAO detectionDAO; + + public BatonStatusHolder(BatonDAO BDAO, DetectionDAO DDAO) { + batonDAO = BDAO; + detectionDAO = DDAO; + this.initStatus(); + } + + private void initStatus() { + var batons = batonDAO.getAll(); + for (Baton baton : batons) { + BatonStatus batonStatus = new BatonStatus( + baton.getMac().toLowerCase(), + baton.getId(), + baton.getName(), + 0, + 0, + false, + null, + -1 + ); + batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); + } + + } + + public List GetAllBatonStatuses() { + // For each baton, fetch latest detection + var batons = batonDAO.getAll(); + for (Baton baton : batons) { + var batonStatus = GetBatonStatus(baton.getId()); + var detection = detectionDAO.latestDetectionByBatonId(baton.getId(), batonStatus.getLastSeen() == null ? Timestamp.from(Instant.ofEpochSecond(0)) : batonStatus.getLastSeen()); + detection.ifPresent(this::updateState); + } + return new ArrayList<>(batonStatusMap.values()); + } + + private void updateState(Detection msg) { + BatonStatus batonStatus = GetBatonStatus(msg.getBatonId()); + if (batonStatus == null) { + batonStatus = createBatonStatus(msg.getBatonId()); + batonStatusMap.put(batonStatus.getMac(), batonStatus); + } + if (batonStatus.getLastSeen() == null) { + batonStatus.setLastSeen(msg.getTimestamp()); + } + if (batonStatus.getLastSeen().after(msg.getTimestamp())) { + return; + } + if (msg.getUptimeMs() < batonStatus.getUptime() - 3000) { + batonStatus.setRebooted(true); + } + batonStatus.setLastSeenSecondsAgo((System.currentTimeMillis() - msg.getTimestamp().getTime()) / 1000); + batonStatus.setLastSeen(msg.getTimestamp()); + batonStatus.setUptime(msg.getUptimeMs() / 1000); + batonStatus.setBattery(msg.getBattery()); + batonStatus.setLastDetectedAtStation(msg.getStationId()); + } + + public BatonStatus GetBatonStatus(Integer batonId) { + if (!batonIdToMac.containsKey(batonId)) { + var baton = batonDAO.getById(batonId); + baton.ifPresent(value -> batonIdToMac.put(batonId, value.getMac().toLowerCase())); + } + String batonMac = batonIdToMac.get(batonId); + return batonStatusMap.get(batonMac); + } + + public BatonStatus createBatonStatus(Integer batonId) { + String batonMac = batonIdToMac.get(batonId); + if (batonMac != null) { + return batonStatusMap.get(batonMac); + } + var baton = batonDAO.getById(batonId); + if (baton.isEmpty()) { + // Non-existing baton + return null; + } + BatonStatus batonStatus = new BatonStatus( + baton.get().getMac().toLowerCase(), + baton.get().getId(), + baton.get().getName(), + 0, + 0, + false, + null, + -1 + ); + batonStatusMap.put(batonStatus.getMac(), batonStatus); + batonIdToMac.put(batonId, batonStatus.getMac()); + return batonStatus; + } + + public void resetRebooted(int batonId) { + var batonStatus = GetBatonStatus(batonId); + if (batonStatus == null) { + return; + } + batonStatus.setRebooted(false); + } +} diff --git a/src/main/java/telraam/monitoring/models/BatonDetection.java b/src/main/java/telraam/monitoring/models/BatonDetection.java new file mode 100644 index 0000000..98f3f2b --- /dev/null +++ b/src/main/java/telraam/monitoring/models/BatonDetection.java @@ -0,0 +1,45 @@ +package telraam.monitoring.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BatonDetection { + @JsonProperty("detected_time") + private Integer detectionTime; + private Integer rssi; + @JsonProperty("team_id") + private Integer teamId; + @JsonProperty("team_name") + private String teamName; + + public BatonDetection(Integer detectionTime, Integer rssi, Integer teamId, String teamName) { + this.detectionTime = detectionTime; + this.rssi = rssi; + this.teamId = teamId; + this.teamName = teamName; + } + + public Integer getDetectionTime() { + return detectionTime; + } + public void setDetectionTime(Integer detectionTime) { + this.detectionTime = detectionTime; + } + public Integer getRssi() { + return rssi; + } + public void setRssi(Integer rssi) { + this.rssi = rssi; + } + public Integer getTeamId() { + return teamId; + } + public void setTeamId(Integer teamId) { + this.teamId = teamId; + } + public String getTeamName() { + return teamName; + } + public void setTeamName(String teamName) { + this.teamName = teamName; + } +} diff --git a/src/main/java/telraam/monitoring/models/BatonStatus.java b/src/main/java/telraam/monitoring/models/BatonStatus.java new file mode 100644 index 0000000..947bd60 --- /dev/null +++ b/src/main/java/telraam/monitoring/models/BatonStatus.java @@ -0,0 +1,113 @@ +package telraam.monitoring.models; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.sql.Timestamp; + +public class BatonStatus { + private String mac; + private Integer id; + private String name; + private Float battery; + // Uptime in seconds + private Long uptime; + private Boolean rebooted; + @JsonProperty("time_since_seen") + private Long lastSeenSecondsAgo; + @JsonIgnore + private Timestamp lastSeen; + @JsonProperty("last_detected_at_station") + private Integer lastDetectedAtStation; + + public BatonStatus(String mac, Integer id, String name, float battery, long uptime, boolean rebooted, Timestamp lastSeen, Integer LDAS) { + this.mac = mac; + this.id = id; + this.name = name; + this.battery = battery; + this.uptime = uptime; + this.rebooted = rebooted; + this.lastSeen = lastSeen; + this.lastSeenSecondsAgo = lastSeen != null ? (System.currentTimeMillis() - lastSeen.getTime()) / 1000 : null; + this.lastDetectedAtStation = LDAS; + } + + // Getters and setters + public String getMac() { + return mac; + } + + public void setMac(String mac) { + this.mac = mac; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Float getBattery() { + return battery; + } + + public void setBattery(Float battery) { + this.battery = battery; + } + + public Long getUptime() { + return uptime; + } + + public void setUptime(Long uptime) { + this.uptime = uptime; + } + + public Boolean getRebooted() { + return rebooted; + } + + public void setRebooted(Boolean rebooted) { + this.rebooted = rebooted; + } + + public Long getLastSeenSecondsAgo() { + return lastSeenSecondsAgo; + } + + public void setLastSeenSecondsAgo(Long lastSeenSecondsAgo) { + this.lastSeenSecondsAgo = lastSeenSecondsAgo; + } + + public Timestamp getLastSeen() { + return lastSeen; + } + + public void setLastSeen(Timestamp lastSeen) { + this.lastSeen = lastSeen; + } + + public Integer getLastDetectedAtStation() { + return lastDetectedAtStation; + } + + public void setLastDetectedAtStation(Integer lastDetectedAtStation) { + this.lastDetectedAtStation = lastDetectedAtStation; + } + + @Override + public String toString() { + return String.format("BatonStatus{mac='%s', id=%d, name='%s', battery=%f, uptime=%d, rebooted=%b, lastSeen=%s, lastSeenSecondsAgo=%d, lastDetectedAtStation=%d}", + mac, id, name, battery, uptime, rebooted, lastSeen, lastSeenSecondsAgo, lastDetectedAtStation); + } +} diff --git a/src/main/java/telraam/monitoring/models/LapCountForTeam.java b/src/main/java/telraam/monitoring/models/LapCountForTeam.java new file mode 100644 index 0000000..f75d8d0 --- /dev/null +++ b/src/main/java/telraam/monitoring/models/LapCountForTeam.java @@ -0,0 +1,17 @@ +package telraam.monitoring.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Map; + +public class LapCountForTeam { + @JsonProperty("team_name") + private String teamName; + @JsonProperty("lap_counts") + private Map lapCounts; + + public LapCountForTeam(String teamName, Map lapCounts) { + this.teamName = teamName; + this.lapCounts = lapCounts; + } +} diff --git a/src/main/java/telraam/monitoring/models/TeamLapInfo.java b/src/main/java/telraam/monitoring/models/TeamLapInfo.java new file mode 100644 index 0000000..3473bd1 --- /dev/null +++ b/src/main/java/telraam/monitoring/models/TeamLapInfo.java @@ -0,0 +1,21 @@ +package telraam.monitoring.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class TeamLapInfo { + @JsonProperty("lap_time") + private long lapTime; + @JsonProperty("timestamp") + private long timestamp; + @JsonProperty("team_id") + private int teamId; + @JsonProperty("team_name") + private String teamName; + + public TeamLapInfo(long lapTime, long timestamp, int teamId, String teamName) { + this.lapTime = lapTime; + this.timestamp = timestamp; + this.teamId = teamId; + this.teamName = teamName; + } +} From 7d4604a87a7d29f5b36cf854d76008810fdf5069 Mon Sep 17 00:00:00 2001 From: topvennie Date: Wed, 8 Mar 2023 16:34:34 +0100 Subject: [PATCH 11/90] Fix query --- src/main/java/telraam/database/daos/DetectionDAO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index baefc4a..419ff18 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -62,7 +62,7 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id Optional latestDetectionByBatonId(@Bind("batonId") int batonId, @Bind("timestamp") Timestamp timestamp); @SqlQuery(""" - WITH bso AS (SELECT teamid, newbatonid, timestamp AS current_timestamp, LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp) next_baton_switch FROM batonswitchover) + WITH bso AS (SELECT teamid, newbatonid, timestamp AS current_timestamp, COALESCE( LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), timestamp + INTERVAL '1 year') AS next_baton_switch FROM batonswitchover) SELECT baton_id, station_id, rssi, timestamp, teamid FROM detection d LEFT JOIN bso ON d.baton_id = bso.newbatonid AND d.timestamp BETWEEN bso.current_timestamp AND bso.next_baton_switch WHERE rssi > :minRssi """) @RegisterBeanMapper(Detection.class) From 283b749cc0bfe40cfc408a96f0f80554188a8e40 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 8 Mar 2023 17:03:23 +0100 Subject: [PATCH 12/90] refactor(monitoring): fixed team-lap-detections, also account batonSwitchOvers --- .../java/telraam/api/MonitoringResource.java | 2 +- .../monitoring/BatonDetectionManager.java | 27 ++++++++++++++++--- .../monitoring/models/BatonDetection.java | 1 + 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java index c9810e1..378e695 100644 --- a/src/main/java/telraam/api/MonitoringResource.java +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -33,7 +33,7 @@ public MonitoringResource(Jdbi jdbi) { this.lapDAO = jdbi.onDemand(LapDAO.class); this.lapSourceDAO = jdbi.onDemand(LapSourceDAO.class); this.batonStatusHolder = new BatonStatusHolder(jdbi.onDemand(BatonDAO.class), jdbi.onDemand(DetectionDAO.class)); - this.batonDetectionManager = new BatonDetectionManager(jdbi.onDemand(DetectionDAO.class), this.teamDAO); + this.batonDetectionManager = new BatonDetectionManager(jdbi.onDemand(DetectionDAO.class), this.teamDAO, jdbi.onDemand(BatonSwitchoverDAO.class)); } @GET diff --git a/src/main/java/telraam/monitoring/BatonDetectionManager.java b/src/main/java/telraam/monitoring/BatonDetectionManager.java index ec35308..e885890 100644 --- a/src/main/java/telraam/monitoring/BatonDetectionManager.java +++ b/src/main/java/telraam/monitoring/BatonDetectionManager.java @@ -1,5 +1,6 @@ package telraam.monitoring; +import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.daos.DetectionDAO; import telraam.database.daos.TeamDAO; import telraam.database.models.Team; @@ -13,23 +14,43 @@ public class BatonDetectionManager { private DetectionDAO detectionDAO; private TeamDAO teamDAO; + private BatonSwitchoverDAO batonSwitchoverDAO; // Map of a baton id to it's detections private Map> batonDetectionMap = new HashMap<>(); private Integer handledDetectionId = 0; - public BatonDetectionManager(DetectionDAO detectionDAO, TeamDAO teamDAO) { + public BatonDetectionManager(DetectionDAO detectionDAO, TeamDAO teamDAO, BatonSwitchoverDAO batonSwitchoverDAO) { this.detectionDAO = detectionDAO; this.teamDAO = teamDAO; + this.batonSwitchoverDAO = batonSwitchoverDAO; } public Map> getBatonDetections() { var detections = detectionDAO.getSinceId(handledDetectionId, Integer.MAX_VALUE); + var batonSwitchOvers = batonSwitchoverDAO.getAll(); // Map of batonIds to team info var teamMap = new HashMap(); var teams = teamDAO.getAll(); - teams.forEach(t -> teamMap.put(t.getBatonId(), t)); + teams.forEach(t -> teamMap.put(t.getId(), t)); detections.forEach(d -> { + Map batonTeamMap = new HashMap<>(); + batonSwitchOvers.forEach(b -> { + if (b.getTimestamp().after(d.getTimestamp())) { + return; + } + if (b.getPreviousBatonId() != null && batonTeamMap.containsKey(b.getPreviousBatonId())) { + if (batonTeamMap.get(b.getPreviousBatonId()).equals(b.getTeamId())) { + batonTeamMap.remove(b.getPreviousBatonId()); + } + } + if (b.getNewBatonId() != null) { + batonTeamMap.put(b.getNewBatonId(), b.getTeamId()); + } + }); + if (!batonTeamMap.containsKey(d.getBatonId())) { + return; + } if (d.getId() > handledDetectionId) { handledDetectionId = d.getId(); } @@ -38,7 +59,7 @@ public Map> getBatonDetections() { batonDetectionMap.put(batonId, new ArrayList<>()); } var batonDetections = batonDetectionMap.get(batonId); - var team = teamMap.get(batonId); + var team = teamMap.get(batonTeamMap.get(batonId)); var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), batonId, team.getName()); batonDetections.add(batonDetection); }); diff --git a/src/main/java/telraam/monitoring/models/BatonDetection.java b/src/main/java/telraam/monitoring/models/BatonDetection.java index 98f3f2b..14797a9 100644 --- a/src/main/java/telraam/monitoring/models/BatonDetection.java +++ b/src/main/java/telraam/monitoring/models/BatonDetection.java @@ -5,6 +5,7 @@ public class BatonDetection { @JsonProperty("detected_time") private Integer detectionTime; + @JsonProperty("rssi") private Integer rssi; @JsonProperty("team_id") private Integer teamId; From 39aa51ba57463fd82dbe89e4a0d62779b95a0594 Mon Sep 17 00:00:00 2001 From: Ewayn Date: Wed, 8 Mar 2023 17:07:46 +0100 Subject: [PATCH 13/90] add api endpoint to know if stations do detections (#99) --- .../java/telraam/api/MonitoringResource.java | 9 +++++ .../monitoring/StationDetectionManager.java | 37 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/main/java/telraam/monitoring/StationDetectionManager.java diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java index 378e695..dc678a7 100644 --- a/src/main/java/telraam/api/MonitoringResource.java +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -24,6 +24,7 @@ public class MonitoringResource { private final BatonStatusHolder batonStatusHolder; private final BatonDetectionManager batonDetectionManager; + private final StationDetectionManager stationDetectionManager; private final TeamDAO teamDAO; private final LapDAO lapDAO; private final LapSourceDAO lapSourceDAO; @@ -34,6 +35,7 @@ public MonitoringResource(Jdbi jdbi) { this.lapSourceDAO = jdbi.onDemand(LapSourceDAO.class); this.batonStatusHolder = new BatonStatusHolder(jdbi.onDemand(BatonDAO.class), jdbi.onDemand(DetectionDAO.class)); this.batonDetectionManager = new BatonDetectionManager(jdbi.onDemand(DetectionDAO.class), this.teamDAO, jdbi.onDemand(BatonSwitchoverDAO.class)); + this.stationDetectionManager = new StationDetectionManager(jdbi.onDemand(DetectionDAO.class), jdbi.onDemand(StationDAO.class)); } @GET @@ -66,6 +68,13 @@ public Map> getTeamDetectionTimes() { return batonDetectionManager.getBatonDetections(); } + @GET + @Path("/stations-latest-detection-time") + @ApiOperation(value = "Get the map of all station ID's to time since last detection") + public Map getStationIDToLatestDetectionTimeMap() { + return stationDetectionManager.timeSinceLastDetectionPerStation(); + } + @GET @Path("/team-lap-times/{lapperId}") @ApiOperation(value = "Get monitoring data that can be used as grafana datasource") diff --git a/src/main/java/telraam/monitoring/StationDetectionManager.java b/src/main/java/telraam/monitoring/StationDetectionManager.java new file mode 100644 index 0000000..7de5274 --- /dev/null +++ b/src/main/java/telraam/monitoring/StationDetectionManager.java @@ -0,0 +1,37 @@ +package telraam.monitoring; + +import telraam.database.daos.DetectionDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.Detection; +import telraam.database.models.Station; + +import java.util.*; +import java.util.stream.Collectors; + +public class StationDetectionManager { + private DetectionDAO detectionDAO; + + private StationDAO stationDAO; + + public StationDetectionManager(DetectionDAO detectionDAO, StationDAO stationDAO) { + this.detectionDAO = detectionDAO; + this.stationDAO = stationDAO; + } + + public Map timeSinceLastDetectionPerStation() { + List stationIdList = stationDAO.getAll().stream().map(Station::getId).toList(); + Map stationIdToTimeSinceLatestDetection = new HashMap<>(); + for (Integer stationId : stationIdList) { + Optional maybeDetection = this.detectionDAO.latestDetectionByStationId(stationId); + + if (maybeDetection.isPresent()) { + Long time = maybeDetection.get().getTimestamp().getTime(); + stationIdToTimeSinceLatestDetection.put(stationId, (System.currentTimeMillis() - time)/1000); + } else { + stationIdToTimeSinceLatestDetection.put(stationId, null); + } + } + return stationIdToTimeSinceLatestDetection; + } +} From 9b76773dc62d3dd93f054df501fcd9f903a44d89 Mon Sep 17 00:00:00 2001 From: topvennie Date: Wed, 8 Mar 2023 17:27:16 +0100 Subject: [PATCH 14/90] Increase max backward distance --- src/main/java/telraam/logic/robustLapper/RobustLapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robustLapper/RobustLapper.java index bb3e974..0477875 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robustLapper/RobustLapper.java @@ -112,7 +112,7 @@ public void calculateLaps() { } else { // We're in a new interval, use the detection with the highest RSSI to update trajectory // Check if new station is more likely to be in front of the runner - if (! (backwardPathDistance(lastStationPosition, currentStationPosition) <= 2)) { + if (! (backwardPathDistance(lastStationPosition, currentStationPosition) <= 3)) { if (isStartBetween(lastStationPosition, currentStationPosition)) { // Add lap if we passed the start line lapTimes.add(detection.getTimestamp()); From d28bbc0dc025d80d520285b70068877d7aa3d0a6 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 8 Mar 2023 17:32:12 +0100 Subject: [PATCH 15/90] feat(monitoring): add stationId to BatonDetection --- .../telraam/monitoring/BatonDetectionManager.java | 2 +- .../telraam/monitoring/models/BatonDetection.java | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/monitoring/BatonDetectionManager.java b/src/main/java/telraam/monitoring/BatonDetectionManager.java index e885890..917e5db 100644 --- a/src/main/java/telraam/monitoring/BatonDetectionManager.java +++ b/src/main/java/telraam/monitoring/BatonDetectionManager.java @@ -60,7 +60,7 @@ public Map> getBatonDetections() { } var batonDetections = batonDetectionMap.get(batonId); var team = teamMap.get(batonTeamMap.get(batonId)); - var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), batonId, team.getName()); + var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(),d.getStationId(), batonId, team.getName()); batonDetections.add(batonDetection); }); return batonDetectionMap; diff --git a/src/main/java/telraam/monitoring/models/BatonDetection.java b/src/main/java/telraam/monitoring/models/BatonDetection.java index 14797a9..38f97d9 100644 --- a/src/main/java/telraam/monitoring/models/BatonDetection.java +++ b/src/main/java/telraam/monitoring/models/BatonDetection.java @@ -1,6 +1,7 @@ package telraam.monitoring.models; import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.models.auth.In; public class BatonDetection { @JsonProperty("detected_time") @@ -9,12 +10,15 @@ public class BatonDetection { private Integer rssi; @JsonProperty("team_id") private Integer teamId; + @JsonProperty("station_id") + private Integer stationId; @JsonProperty("team_name") private String teamName; - public BatonDetection(Integer detectionTime, Integer rssi, Integer teamId, String teamName) { + public BatonDetection(Integer detectionTime, Integer rssi, Integer stationId, Integer teamId, String teamName) { this.detectionTime = detectionTime; this.rssi = rssi; + this.stationId = stationId; this.teamId = teamId; this.teamName = teamName; } @@ -37,6 +41,12 @@ public Integer getTeamId() { public void setTeamId(Integer teamId) { this.teamId = teamId; } + public Integer getStationId() { + return stationId; + } + public void setStationId(Integer stationId) { + this.stationId = stationId; + } public String getTeamName() { return teamName; } From 818f818e7610228f43f80f9f6539d142bb618220 Mon Sep 17 00:00:00 2001 From: Iwijn Date: Wed, 8 Mar 2023 18:03:39 +0100 Subject: [PATCH 16/90] change key --- src/main/java/telraam/api/MonitoringResource.java | 4 ++-- .../telraam/monitoring/StationDetectionManager.java | 12 +++++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java index dc678a7..0a925ea 100644 --- a/src/main/java/telraam/api/MonitoringResource.java +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -70,8 +70,8 @@ public Map> getTeamDetectionTimes() { @GET @Path("/stations-latest-detection-time") - @ApiOperation(value = "Get the map of all station ID's to time since last detection") - public Map getStationIDToLatestDetectionTimeMap() { + @ApiOperation(value = "Get the map of all station name to time since last detection") + public Map getStationIDToLatestDetectionTimeMap() { return stationDetectionManager.timeSinceLastDetectionPerStation(); } diff --git a/src/main/java/telraam/monitoring/StationDetectionManager.java b/src/main/java/telraam/monitoring/StationDetectionManager.java index 7de5274..aca26da 100644 --- a/src/main/java/telraam/monitoring/StationDetectionManager.java +++ b/src/main/java/telraam/monitoring/StationDetectionManager.java @@ -19,17 +19,15 @@ public StationDetectionManager(DetectionDAO detectionDAO, StationDAO stationDAO) this.stationDAO = stationDAO; } - public Map timeSinceLastDetectionPerStation() { + public Map timeSinceLastDetectionPerStation() { List stationIdList = stationDAO.getAll().stream().map(Station::getId).toList(); - Map stationIdToTimeSinceLatestDetection = new HashMap<>(); + Map stationIdToTimeSinceLatestDetection = new HashMap<>(); for (Integer stationId : stationIdList) { Optional maybeDetection = this.detectionDAO.latestDetectionByStationId(stationId); - - if (maybeDetection.isPresent()) { + Optional maybeStation = this.stationDAO.getById(stationId); + if (maybeDetection.isPresent() && maybeStation.isPresent()) { Long time = maybeDetection.get().getTimestamp().getTime(); - stationIdToTimeSinceLatestDetection.put(stationId, (System.currentTimeMillis() - time)/1000); - } else { - stationIdToTimeSinceLatestDetection.put(stationId, null); + stationIdToTimeSinceLatestDetection.put(maybeStation.get().getName(), (System.currentTimeMillis() - time)/1000); } } return stationIdToTimeSinceLatestDetection; From b03329fd5829142a607df1868a000ed448d9a0a1 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 8 Mar 2023 18:33:16 +0100 Subject: [PATCH 17/90] fix(tests): init data at first request --- src/main/java/telraam/monitoring/BatonStatusHolder.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java index db59421..9966cee 100644 --- a/src/main/java/telraam/monitoring/BatonStatusHolder.java +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -19,14 +19,16 @@ public class BatonStatusHolder { private BatonDAO batonDAO; private DetectionDAO detectionDAO; + private boolean initialized = false; public BatonStatusHolder(BatonDAO BDAO, DetectionDAO DDAO) { batonDAO = BDAO; detectionDAO = DDAO; - this.initStatus(); } private void initStatus() { + if (initialized) return; + initialized = true; var batons = batonDAO.getAll(); for (Baton baton : batons) { BatonStatus batonStatus = new BatonStatus( @@ -45,6 +47,7 @@ private void initStatus() { } public List GetAllBatonStatuses() { + this.initStatus(); // For each baton, fetch latest detection var batons = batonDAO.getAll(); for (Baton baton : batons) { @@ -78,6 +81,7 @@ private void updateState(Detection msg) { } public BatonStatus GetBatonStatus(Integer batonId) { + this.initStatus(); if (!batonIdToMac.containsKey(batonId)) { var baton = batonDAO.getById(batonId); baton.ifPresent(value -> batonIdToMac.put(batonId, value.getMac().toLowerCase())); @@ -87,6 +91,7 @@ public BatonStatus GetBatonStatus(Integer batonId) { } public BatonStatus createBatonStatus(Integer batonId) { + this.initStatus(); String batonMac = batonIdToMac.get(batonId); if (batonMac != null) { return batonStatusMap.get(batonMac); @@ -112,6 +117,7 @@ public BatonStatus createBatonStatus(Integer batonId) { } public void resetRebooted(int batonId) { + this.initStatus(); var batonStatus = GetBatonStatus(batonId); if (batonStatus == null) { return; From ac75872d317c70c3e2d86a239ce4ea8b6f1b9646 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 8 Mar 2023 23:52:22 +0100 Subject: [PATCH 18/90] fix(monitoring): also include detections with the same timestamp to always return a detection if one existed --- src/main/java/telraam/database/daos/DetectionDAO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index 419ff18..c50452e 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -57,7 +57,7 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id List getSinceId(@Bind("id") int id, @Bind("limit") int limit); - @SqlQuery("SELECT * FROM detection WHERE baton_id = :batonId AND timestamp > :timestamp ORDER BY timestamp DESC LIMIT 1") + @SqlQuery("SELECT * FROM detection WHERE baton_id = :batonId AND timestamp >= :timestamp ORDER BY timestamp DESC LIMIT 1") @RegisterBeanMapper(Detection.class) Optional latestDetectionByBatonId(@Bind("batonId") int batonId, @Bind("timestamp") Timestamp timestamp); From 9db4acaa98783f08342a4b0e9053ab1682631967 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Mon, 25 Mar 2024 20:22:35 +0100 Subject: [PATCH 19/90] feat(BatonStatusHolder): implement default dict behavior in a custom getter --- .../java/telraam/database/daos/BatonDAO.java | 4 +++ .../telraam/monitoring/BatonStatusHolder.java | 29 +++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/database/daos/BatonDAO.java b/src/main/java/telraam/database/daos/BatonDAO.java index f0859d1..2aefda9 100644 --- a/src/main/java/telraam/database/daos/BatonDAO.java +++ b/src/main/java/telraam/database/daos/BatonDAO.java @@ -28,6 +28,10 @@ public interface BatonDAO extends DAO { @RegisterBeanMapper(Baton.class) Optional getById(@Bind("id") int id); + @SqlQuery("SELECT * FROM baton WHERE mac = :mac") + @RegisterBeanMapper(Baton.class) + Optional getByMac(@Bind("mac") String mac); + @Override @SqlUpdate("DELETE FROM baton WHERE id = :id") @RegisterBeanMapper(Baton.class) diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java index 9966cee..e3e4f36 100644 --- a/src/main/java/telraam/monitoring/BatonStatusHolder.java +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Optional; public class BatonStatusHolder { // Map from batonMac to batonStatus @@ -43,6 +44,30 @@ private void initStatus() { ); batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); } + } + + private BatonStatus getStatusForBaton(String batonMac) { + BatonStatus batonStatus = batonStatusMap.get(batonMac); + if (batonStatus == null) { + Optional optionalBaton = batonDAO.getByMac(batonMac); + if (optionalBaton.isEmpty()) { + return null; + } + Baton baton = optionalBaton.get(); + + batonStatus = new BatonStatus( + baton.getMac().toLowerCase(), + baton.getId(), + baton.getName(), + 0, + 0, + false, + null, + -1 + ); + batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); + } + return batonStatus; } @@ -87,14 +112,14 @@ public BatonStatus GetBatonStatus(Integer batonId) { baton.ifPresent(value -> batonIdToMac.put(batonId, value.getMac().toLowerCase())); } String batonMac = batonIdToMac.get(batonId); - return batonStatusMap.get(batonMac); + return getStatusForBaton(batonMac); } public BatonStatus createBatonStatus(Integer batonId) { this.initStatus(); String batonMac = batonIdToMac.get(batonId); if (batonMac != null) { - return batonStatusMap.get(batonMac); + return getStatusForBaton(batonMac); } var baton = batonDAO.getById(batonId); if (baton.isEmpty()) { From c1d8482760895e85aa9e462038fb50ea87478980 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 20:27:51 +0100 Subject: [PATCH 20/90] quick cleanup --- .gitignore | 4 +- .idea/$PRODUCT_WORKSPACE_FILE$ | 18 -- .idea/.gitignore | 2 - .idea/.name | 1 - .idea/compiler.xml | 6 - .idea/dataSources.xml | 23 -- .idea/jarRepositories.xml | 25 -- .idea/jpa-buddy.xml | 6 - .idea/misc.xml | 8 - .idea/runConfigurations/Telraam__build_.xml | 23 -- .../Telraam__migrateDevelopmentDatabase_.xml | 21 -- .../Telraam__migrateProductionDatabase_.xml | 21 -- .../Telraam__migrateTestingDatabase_.xml | 21 -- .idea/runConfigurations/Telraam__runDev_.xml | 21 -- .idea/runConfigurations/Telraam__runProd_.xml | 21 -- .idea/runConfigurations/Telraam__test_.xml | 26 -- .../Telraam__test_force_.xml | 26 -- .idea/sonarlint-state.xml | 6 - .idea/sonarlint.xml | 8 - .idea/sqldialects.xml | 7 - .idea/vcs.xml | 6 - src/main/java/telraam/App.java | 2 +- src/main/java/telraam/database/models/Id.java | 19 -- .../RobustLapper.java | 2 +- .../logic/{ => simple}/SimpleLapper.java | 3 +- .../telraam/logic/viterbi/ViterbiLapper.java | 292 ------------------ .../viterbi/ViterbiLapperConfiguration.java | 42 --- .../logic/viterbi/ViterbiLapperResource.java | 61 ---- .../algorithm/InvalidParameterException.java | 7 - .../viterbi/algorithm/ViterbiAlgorithm.java | 127 -------- .../logic/viterbi/algorithm/ViterbiModel.java | 30 -- .../logic/viterbi/algorithm/ViterbiState.java | 25 -- src/main/java/telraam/station/Fetcher.java | 2 + .../station/{ => models}/RonnyDetection.java | 2 +- .../station/{ => models}/RonnyResponse.java | 2 +- src/main/resources/banner.txt | 9 +- .../java/telraam/logic/SimpleLapperTest.java | 1 + 37 files changed, 20 insertions(+), 906 deletions(-) delete mode 100644 .idea/$PRODUCT_WORKSPACE_FILE$ delete mode 100644 .idea/.gitignore delete mode 100644 .idea/.name delete mode 100644 .idea/compiler.xml delete mode 100644 .idea/dataSources.xml delete mode 100644 .idea/jarRepositories.xml delete mode 100644 .idea/jpa-buddy.xml delete mode 100644 .idea/misc.xml delete mode 100644 .idea/runConfigurations/Telraam__build_.xml delete mode 100644 .idea/runConfigurations/Telraam__migrateDevelopmentDatabase_.xml delete mode 100644 .idea/runConfigurations/Telraam__migrateProductionDatabase_.xml delete mode 100644 .idea/runConfigurations/Telraam__migrateTestingDatabase_.xml delete mode 100644 .idea/runConfigurations/Telraam__runDev_.xml delete mode 100644 .idea/runConfigurations/Telraam__runProd_.xml delete mode 100644 .idea/runConfigurations/Telraam__test_.xml delete mode 100644 .idea/runConfigurations/Telraam__test_force_.xml delete mode 100644 .idea/sonarlint-state.xml delete mode 100644 .idea/sonarlint.xml delete mode 100644 .idea/sqldialects.xml delete mode 100644 .idea/vcs.xml delete mode 100644 src/main/java/telraam/database/models/Id.java rename src/main/java/telraam/logic/{robustLapper => robust}/RobustLapper.java (99%) rename src/main/java/telraam/logic/{ => simple}/SimpleLapper.java (97%) delete mode 100644 src/main/java/telraam/logic/viterbi/ViterbiLapper.java delete mode 100644 src/main/java/telraam/logic/viterbi/ViterbiLapperConfiguration.java delete mode 100644 src/main/java/telraam/logic/viterbi/ViterbiLapperResource.java delete mode 100644 src/main/java/telraam/logic/viterbi/algorithm/InvalidParameterException.java delete mode 100644 src/main/java/telraam/logic/viterbi/algorithm/ViterbiAlgorithm.java delete mode 100644 src/main/java/telraam/logic/viterbi/algorithm/ViterbiModel.java delete mode 100644 src/main/java/telraam/logic/viterbi/algorithm/ViterbiState.java rename src/main/java/telraam/station/{ => models}/RonnyDetection.java (90%) rename src/main/java/telraam/station/{ => models}/RonnyResponse.java (87%) diff --git a/.gitignore b/.gitignore index b55c818..95ddd25 100644 --- a/.gitignore +++ b/.gitignore @@ -192,4 +192,6 @@ flycheck_*.el !gradle-wrapper.jar -node_modules/ \ No newline at end of file +node_modules/ + +.idea \ No newline at end of file diff --git a/.idea/$PRODUCT_WORKSPACE_FILE$ b/.idea/$PRODUCT_WORKSPACE_FILE$ deleted file mode 100644 index 96ce66b..0000000 --- a/.idea/$PRODUCT_WORKSPACE_FILE$ +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 5c98b42..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Default ignored files -/workspace.xml \ No newline at end of file diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 780c8da..0000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -telraam \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index 659bf43..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index f37c315..0000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - postgresql - true - org.postgresql.Driver - jdbc:postgresql://localhost:5432/telraam_dev - - - sqlite.xerial - true - org.sqlite.JDBC - jdbc:sqlite::memory: - - - postgresql - true - org.postgresql.Driver - jdbc:postgresql://localhost:5432/telraam_dev - - - \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml deleted file mode 100644 index b3e9cbd..0000000 --- a/.idea/jarRepositories.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/jpa-buddy.xml b/.idea/jpa-buddy.xml deleted file mode 100644 index d08f400..0000000 --- a/.idea/jpa-buddy.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 240ddf3..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__build_.xml b/.idea/runConfigurations/Telraam__build_.xml deleted file mode 100644 index 0d73339..0000000 --- a/.idea/runConfigurations/Telraam__build_.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - true - true - false - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__migrateDevelopmentDatabase_.xml b/.idea/runConfigurations/Telraam__migrateDevelopmentDatabase_.xml deleted file mode 100644 index 202127f..0000000 --- a/.idea/runConfigurations/Telraam__migrateDevelopmentDatabase_.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__migrateProductionDatabase_.xml b/.idea/runConfigurations/Telraam__migrateProductionDatabase_.xml deleted file mode 100644 index ffc82b4..0000000 --- a/.idea/runConfigurations/Telraam__migrateProductionDatabase_.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__migrateTestingDatabase_.xml b/.idea/runConfigurations/Telraam__migrateTestingDatabase_.xml deleted file mode 100644 index b2859c2..0000000 --- a/.idea/runConfigurations/Telraam__migrateTestingDatabase_.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__runDev_.xml b/.idea/runConfigurations/Telraam__runDev_.xml deleted file mode 100644 index c3766a2..0000000 --- a/.idea/runConfigurations/Telraam__runDev_.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__runProd_.xml b/.idea/runConfigurations/Telraam__runProd_.xml deleted file mode 100644 index 0f6b693..0000000 --- a/.idea/runConfigurations/Telraam__runProd_.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__test_.xml b/.idea/runConfigurations/Telraam__test_.xml deleted file mode 100644 index fdffce2..0000000 --- a/.idea/runConfigurations/Telraam__test_.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/runConfigurations/Telraam__test_force_.xml b/.idea/runConfigurations/Telraam__test_force_.xml deleted file mode 100644 index f18cffe..0000000 --- a/.idea/runConfigurations/Telraam__test_force_.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - true - - - \ No newline at end of file diff --git a/.idea/sonarlint-state.xml b/.idea/sonarlint-state.xml deleted file mode 100644 index 0b9835d..0000000 --- a/.idea/sonarlint-state.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - 1634050067000 - - \ No newline at end of file diff --git a/.idea/sonarlint.xml b/.idea/sonarlint.xml deleted file mode 100644 index 4b4f6a7..0000000 --- a/.idea/sonarlint.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml deleted file mode 100644 index 0840fc3..0000000 --- a/.idea/sqldialects.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index a4ba783..243edc8 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -16,7 +16,7 @@ import telraam.healthchecks.TemplateHealthCheck; import telraam.logic.Lapper; import telraam.logic.external.ExternalLapper; -import telraam.logic.robustLapper.RobustLapper; +import telraam.logic.robust.RobustLapper; import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; diff --git a/src/main/java/telraam/database/models/Id.java b/src/main/java/telraam/database/models/Id.java deleted file mode 100644 index 97132af..0000000 --- a/src/main/java/telraam/database/models/Id.java +++ /dev/null @@ -1,19 +0,0 @@ -package telraam.database.models; - -public class Id { - - private int id; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public String toString() { - return String.format("Id: %d", id); - } -} \ No newline at end of file diff --git a/src/main/java/telraam/logic/robustLapper/RobustLapper.java b/src/main/java/telraam/logic/robust/RobustLapper.java similarity index 99% rename from src/main/java/telraam/logic/robustLapper/RobustLapper.java rename to src/main/java/telraam/logic/robust/RobustLapper.java index 0477875..07335c4 100644 --- a/src/main/java/telraam/logic/robustLapper/RobustLapper.java +++ b/src/main/java/telraam/logic/robust/RobustLapper.java @@ -1,4 +1,4 @@ -package telraam.logic.robustLapper; +package telraam.logic.robust; import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; diff --git a/src/main/java/telraam/logic/SimpleLapper.java b/src/main/java/telraam/logic/simple/SimpleLapper.java similarity index 97% rename from src/main/java/telraam/logic/SimpleLapper.java rename to src/main/java/telraam/logic/simple/SimpleLapper.java index 5ed367e..6acc326 100644 --- a/src/main/java/telraam/logic/SimpleLapper.java +++ b/src/main/java/telraam/logic/simple/SimpleLapper.java @@ -1,10 +1,11 @@ -package telraam.logic; +package telraam.logic.simple; import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; import telraam.database.daos.LapDAO; import telraam.database.daos.LapSourceDAO; import telraam.database.models.*; +import telraam.logic.Lapper; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/telraam/logic/viterbi/ViterbiLapper.java b/src/main/java/telraam/logic/viterbi/ViterbiLapper.java deleted file mode 100644 index 980d891..0000000 --- a/src/main/java/telraam/logic/viterbi/ViterbiLapper.java +++ /dev/null @@ -1,292 +0,0 @@ -package telraam.logic.viterbi; - -import io.dropwizard.jersey.setup.JerseyEnvironment; -import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.*; -import telraam.database.models.*; -import telraam.logic.Lapper; -import telraam.logic.viterbi.algorithm.ViterbiAlgorithm; -import telraam.logic.viterbi.algorithm.ViterbiModel; -import telraam.logic.viterbi.algorithm.ViterbiState; - -import java.sql.Time; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class ViterbiLapper implements Lapper { - static final String SOURCE_NAME = "viterbi-lapper"; - - private final ViterbiLapperConfiguration config; - private Map currentStates; - private final Jdbi jdbi; - private final int lapSourceId; - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - private boolean debounceScheduled; - private final Logger logger = Logger.getLogger(ViterbiLapper.class.getName()); - - public ViterbiLapper(Jdbi jdbi) { - this(jdbi, new ViterbiLapperConfiguration()); - } - - public ViterbiLapper(Jdbi jdbi, ViterbiLapperConfiguration configuration) { - this.jdbi = jdbi; - this.config = configuration; - this.currentStates = new HashMap<>(); - this.debounceScheduled = false; - - LapSourceDAO lapSourceDAO = jdbi.onDemand(LapSourceDAO.class); - - lapSourceDAO.getByName(ViterbiLapper.SOURCE_NAME).orElseThrow(); - - this.lapSourceId = lapSourceDAO.getByName(ViterbiLapper.SOURCE_NAME).get().getId(); - } - - - private ViterbiModel createViterbiModel() { - StationDAO stationDAO = jdbi.onDemand(StationDAO.class); - - // We will construct one segment for each station, which will represent its - // neighbourhood. - List stations = stationDAO.getAll(); - stations.sort(Comparator.comparing(Station::getDistanceFromStart)); - - - // *********************************** - // Build detection probability mapping - // *********************************** - Map> emissionProbabilities = new HashMap<>(); - for (int segmentNum = 0; segmentNum < stations.size(); segmentNum++) { - Map probas = new HashMap<>(); - for (int stationNum = 0; stationNum < stations.size(); stationNum++) { - int stationId = stations.get(stationNum).getId(); - if (segmentNum == stationNum) { - probas.put(stationId, this.config.SAME_STATION_DETECTION_CHANCE); - } else { - probas.put(stationId, this.config.BASE_DETECTION_CHANCE); - } - } - emissionProbabilities.put(segmentNum, probas); - } - - // ************************************ - // Build transition probability mapping - // ************************************ - Map> transitionProbabilities = new HashMap<>(); - for (int prevSegment = 0; prevSegment < stations.size(); prevSegment++) { - Map probas = new HashMap<>(); - - // a station is skipped when it is broken, or when all detections are missed - // TODO: this currently does not take into account detections by other stations - double skipStationProbability = this.config.BROKEN_STATION_PROBABILITY + Math.pow( - 1 - this.config.SAME_STATION_DETECTION_CHANCE, - this.config.EXPECTED_NUM_DETECTIONS - ); - - // calculate amount of steps this way so that backwards steps are rounded down - // and forward steps is rounded up (because we'd like to assume people run in the right direction) - int numStepsBackwards = (stations.size() - 1) / 2; - int numStepsForwards = stations.size() - 1 - numStepsBackwards; - - // This represents the odds (sameStationWeight against one) of staying on the same station - // "how much more likely is it to stay, compared to moving" - double sameStationWeight = (1 - this.config.BROKEN_STATION_PROBABILITY) * this.config.EXPECTED_NUM_DETECTIONS; - // add 2: one unit of weight for running forwards, one for running backwards - probas.put(prevSegment, sameStationWeight / (sameStationWeight + 2)); - - // transition probabilities for running forwards. - // To be precise: these probabilities should represent the probability that you will be at nextSegment - // when the next detection happens. So assuming that you cannot be detected when you are in segment 2, - // the transition probabilities towards segment 2 should always be 0. - // This is because the viterbi algorithm runs in discrete time-steps, where each step corresponds - // to a single detection (and is only vaguely related to the passage of time or distance). - double remainingProbabilityMass = 1 / (sameStationWeight + 2); - for (int i = 1; i <= numStepsForwards; i++) { - // compute next segment index - int nextSegment = Math.floorMod(prevSegment + i, stations.size()); - double proba = remainingProbabilityMass; - if (i < numStepsForwards) { - // multiply by the probability that this station was not skipped. - // When this is the final step, we do not consider the possibility of skipping anymore - // (so that probabilities add up to 1) - proba *= (1 - skipStationProbability); - } - probas.put(nextSegment, proba); - - // subtract the used amount of probability mass - remainingProbabilityMass -= proba; - } - - // transition probabilities for running backwards - // refer to above comments - remainingProbabilityMass = 1 / (sameStationWeight + 2); - for (int i = 1; i <= numStepsBackwards; i++) { - int nextSegment = Math.floorMod(prevSegment - i, stations.size()); - double proba = remainingProbabilityMass; - if (i < numStepsBackwards) { - proba *= (1 - skipStationProbability); - } - probas.put(nextSegment, proba); - remainingProbabilityMass -= proba; - } - - transitionProbabilities.put(prevSegment, probas); - } - - return new ViterbiModel<>( - stations.stream().map(Station::getId).collect(Collectors.toSet()), - IntStream.range(0, stations.size()).boxed().collect(Collectors.toSet()), - transitionProbabilities, - emissionProbabilities, - calculateStartProbabilities() - ); - } - - public Map> getProbabilities() { - Map> ret = new HashMap<>(); - for (Map.Entry entry : this.currentStates.entrySet()) { - ret.put(entry.getKey(), entry.getValue().probabilities()); - } - return ret; - } - - public Map>> getLapTimes() { - Map>> ret = new HashMap<>(); - for (Map.Entry entry : this.currentStates.entrySet()) { - ret.put(entry.getKey(), entry.getValue().lapTimestamps()); - } - return ret; - } - - private Map calculateStartProbabilities() { - StationDAO stationDAO = jdbi.onDemand(StationDAO.class); - List stations = stationDAO.getAll(); - int numStations = stations.size(); - - Map ret = new HashMap<>(); - - ret.put(0, 1.0 - (numStations - 1) * this.config.RESTART_PROBABILITY); - for (int i = 1; i < numStations; i++) { - ret.put(i, this.config.RESTART_PROBABILITY); - } - - return ret; - } - - @Override - public synchronized void handle(Detection msg) { - if (msg.getRssi() < -77) { - return; - } - if (!this.debounceScheduled) { - // TODO: this might be better as an atomic - this.debounceScheduled = true; - this.scheduler.schedule(() -> { - try { - this.calculateLaps(); - } catch (Exception e) { - logger.severe(e.getMessage()); - } - this.debounceScheduled = false; - }, this.config.DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); - } - } - - public synchronized void calculateLaps() { - System.out.println("Calculating laps"); - - TeamDAO teamDAO = this.jdbi.onDemand(TeamDAO.class); - DetectionDAO detectionDAO = this.jdbi.onDemand(DetectionDAO.class); - LapDAO lapDAO = this.jdbi.onDemand(LapDAO.class); - BatonSwitchoverDAO batonSwitchoverDAO = this.jdbi.onDemand(BatonSwitchoverDAO.class); - LapSourceSwitchoverDAO lapSourceSwitchoverDAO = this.jdbi.onDemand(LapSourceSwitchoverDAO.class); - List teams = teamDAO.getAll(); - List switchovers = batonSwitchoverDAO.getAll(); - - Optional maybeFirstLapSourceSwitchover = lapSourceSwitchoverDAO.getAll().stream().filter((x) -> x.getNewLapSource() == 3).findFirst(); - Timestamp firstSwitchover = maybeFirstLapSourceSwitchover.map(LapSourceSwitchover::getTimestamp).orElse(new Timestamp(0)); - - // TODO: stream these from the database - List detections = detectionDAO.getAll(); - detections.removeIf((detection) -> detection.getRssi() < -77 || detection.getTimestamp().before(firstSwitchover)); - detections.sort(Comparator.comparing(Detection::getTimestamp)); - - // we create a viterbi model each time because the set of stations is not static - ViterbiModel viterbiModel = createViterbiModel(); - - Map> viterbis = teams.stream() - .collect(Collectors.toMap(Team::getId, _team -> new ViterbiAlgorithm<>(viterbiModel))); - - Map batonIdToTeamId = new HashMap<>(); - - int switchoverIndex = 0; - - for (Detection detection : detections) { - while (switchoverIndex < switchovers.size() && switchovers.get(switchoverIndex).getTimestamp().before(detection.getTimestamp())) { - BatonSwitchover switchover = switchovers.get(switchoverIndex); - batonIdToTeamId.put(switchover.getNewBatonId(), switchover.getTeamId()); - switchoverIndex += 1; - } - - if (batonIdToTeamId.containsKey(detection.getBatonId())) { - int teamId = batonIdToTeamId.get(detection.getBatonId()); - viterbis.get(teamId).observe(detection.getStationId(), detection.getTimestamp()); - } - } - - this.currentStates = viterbis.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getState())); - - // We made a new estimation of the lap count, now we can update the database state to match - - Map> lapsByTeam = teams.stream().collect(Collectors.toMap(Team::getId, x -> new TreeSet<>(Comparator.comparing(Lap::getTimestamp)))); - - for (Lap lap : lapDAO.getAllBySource(this.lapSourceId)) { - lapsByTeam.get(lap.getTeamId()).add(lap); - } - - for (Map.Entry entry : this.currentStates.entrySet()) { - int teamId = entry.getKey(); - TreeSet laps = lapsByTeam.get(teamId); - - ViterbiState state = entry.getValue(); - - Set currentLaps = laps.stream().map(Lap::getTimestamp).collect(Collectors.toSet()); - Set predictedLaps = state.lapTimestamps().get(state.mostLikelySegment()); - - Set toRemove = new TreeSet<>(currentLaps); - toRemove.removeAll(predictedLaps); - - Set toAdd = new TreeSet<>(predictedLaps); - toAdd.removeAll(currentLaps); - - for (Timestamp timestamp : toRemove) { - lapDAO.removeByTeamAndTimestamp(teamId, timestamp); - } - - for (Timestamp timestamp : toAdd) { - lapDAO.insert(new Lap(teamId, this.lapSourceId, timestamp)); - } - } - - System.out.println("Done calculating laps"); - } - - @Override - public void registerAPI(JerseyEnvironment jersey) { - jersey.register(new ViterbiLapperResource(this)); - } - - public ViterbiLapperConfiguration getConfig() { - return this.config; - } - - public ViterbiModel getModel() { - return this.createViterbiModel(); - } -} diff --git a/src/main/java/telraam/logic/viterbi/ViterbiLapperConfiguration.java b/src/main/java/telraam/logic/viterbi/ViterbiLapperConfiguration.java deleted file mode 100644 index 0c1c8ce..0000000 --- a/src/main/java/telraam/logic/viterbi/ViterbiLapperConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -package telraam.logic.viterbi; - -public class ViterbiLapperConfiguration { - public double RESTART_PROBABILITY; // The probability that the runners will start the race in a different spot than the start/finish line (should only happen on complete restarts) - public int DEBOUNCE_TIMEOUT; // The amount of time detections are debounced for in seconds - - // probability that you will be for detection in the segment corresponding to a station - public double SAME_STATION_DETECTION_CHANCE; - - // the probability that you will be detected at a random station ("noise" detections) - public double BASE_DETECTION_CHANCE; - - // the probability that an individual station is down at any moment in time - // ~= downtime / total time. - // It is not that important that this parameter is estimated correctly (which would be very hard to do) - // it is better to interpret this as the system's eagerness to assume that a station was not working - // when trying to explain a series of detections. - public double BROKEN_STATION_PROBABILITY; - - // The amount of times we expect a runner to be detected when passing by a station, given that the station is alive. - // - // The higher this parameter, the more 'evidence' (= detections) the system will require - // in order to change the predicted location - so, the predictions will be less sensitive to noise detections - // at different stations. - // Consequently, it is better to under-estimate this parameter than to over-estimate it. - public double EXPECTED_NUM_DETECTIONS; - - public ViterbiLapperConfiguration() { - this.RESTART_PROBABILITY = 0.001; - this.DEBOUNCE_TIMEOUT = 10; - - // ballpark estimates extracted from test event data - // IMPORTANT: these numbers are only valid assuming that detection are filtered for rssi >=-70 - // (ask @iasoon for details) - this.SAME_STATION_DETECTION_CHANCE = 0.90; - this.BASE_DETECTION_CHANCE = 0.10; - this.EXPECTED_NUM_DETECTIONS = 3; - - - this.BROKEN_STATION_PROBABILITY = 0.01; - } -} diff --git a/src/main/java/telraam/logic/viterbi/ViterbiLapperResource.java b/src/main/java/telraam/logic/viterbi/ViterbiLapperResource.java deleted file mode 100644 index 3b1de23..0000000 --- a/src/main/java/telraam/logic/viterbi/ViterbiLapperResource.java +++ /dev/null @@ -1,61 +0,0 @@ -package telraam.logic.viterbi; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import telraam.logic.viterbi.algorithm.ViterbiModel; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import java.sql.Timestamp; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@Path("/lappers/viterbi") -@Api("/lappers/viterbi") -@Produces(MediaType.APPLICATION_JSON) -public class ViterbiLapperResource { - private final ViterbiLapper lapper; - - public ViterbiLapperResource(ViterbiLapper lapper) { - this.lapper = lapper; - } - - @GET - @Path("/probabilities") - @ApiOperation(value = "Get lapper position probabilities") - public Map> getProbabilities() { - return this.lapper.getProbabilities(); - } - - @GET - @Path("/lap-times") - @ApiOperation(value = "Get lapper estimated laps") - public Map>> getLapTimes() { - return this.lapper.getLapTimes(); - } - - @GET - @Path("/configuration") - @ApiOperation(value = "Get lapper configuration") - public ViterbiLapperConfiguration getConfiguration() { - return this.lapper.getConfig(); - } - - @GET - @Path("/model") - @ApiOperation(value = "Get Viterbi model") - public ViterbiModel getModel() { - return this.lapper.getModel(); - } - - @GET - @Path("/recalculate") - @ApiOperation(value = "Recalculate Viterbi rounds") - public String recalculateRounds() { - this.lapper.calculateLaps(); - return "Recalculated rounds"; - } -} diff --git a/src/main/java/telraam/logic/viterbi/algorithm/InvalidParameterException.java b/src/main/java/telraam/logic/viterbi/algorithm/InvalidParameterException.java deleted file mode 100644 index 632bf2d..0000000 --- a/src/main/java/telraam/logic/viterbi/algorithm/InvalidParameterException.java +++ /dev/null @@ -1,7 +0,0 @@ -package telraam.logic.viterbi.algorithm; - -public class InvalidParameterException extends RuntimeException { - public InvalidParameterException(String s) { - super(s); - } -} diff --git a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiAlgorithm.java b/src/main/java/telraam/logic/viterbi/algorithm/ViterbiAlgorithm.java deleted file mode 100644 index 2f4e82f..0000000 --- a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiAlgorithm.java +++ /dev/null @@ -1,127 +0,0 @@ -package telraam.logic.viterbi.algorithm; - -import io.swagger.models.auth.In; - -import java.sql.Time; -import java.sql.Timestamp; -import java.util.*; - -/** - * The class performing the Viterbi algorithm. - * @param The type of the observations. - */ -public class ViterbiAlgorithm { - private final ViterbiModel model; - - private ViterbiState lastState; - - public ViterbiAlgorithm(ViterbiModel viterbiModel) { - this.model = viterbiModel; - - this.verifyProbabilities(); - - // Set up the initial probabilities - int numSegments = this.model.getHiddenStates().size(); - Map probabilities = new HashMap<>(); - Map previousSegments = new HashMap<>(); - Map> lapTimestamps = new HashMap<>(); - - for (Map.Entry entry : viterbiModel.getStartProbabilities().entrySet()) { - probabilities.put(entry.getKey(), entry.getValue()); - previousSegments.put(entry.getKey(), 0); - lapTimestamps.put(entry.getKey(), new TreeSet<>()); - } - - this.lastState = new ViterbiState(probabilities, previousSegments, lapTimestamps); - } - - /** - * Verify that the given probabilities are valid. - * @throws InvalidParameterException If the probabilities were not valid. - */ - private void verifyProbabilities() { - if (!this.model.getTransitionProbabilities().keySet().equals(this.model.getHiddenStates())) { - throw new InvalidParameterException("Invalid key set for transition probabilities"); - } - - for (Integer state : this.model.getHiddenStates()) { - if (!this.model.getTransitionProbabilities().get(state).keySet().equals(this.model.getHiddenStates())) { - throw new InvalidParameterException("Invalid key set for transition probabilities for state " + state); - } - } - - if (!this.model.getEmitProbabilities().keySet().equals(this.model.getHiddenStates())) { - throw new InvalidParameterException("Invalid key set for emission probabilities: " + this.model.getEmitProbabilities().keySet() + " != " + this.model.getHiddenStates()); - } - - for (Integer state : this.model.getHiddenStates()) { - if (!this.model.getTransitionProbabilities().get(state).keySet().equals(this.model.getHiddenStates())) { - throw new InvalidParameterException( - "Invalid key set for emission probabilities for state " + - state + - ": " + - this.model.getTransitionProbabilities().get(state).keySet() + - " != " + - this.model.getObservations() - ); - } - } - } - - /** - * Handle an observation. - * @param observation The observation to process. - * @param observationTimestamp The timestamp when this observation was made - */ - public void observe(O observation, Timestamp observationTimestamp) { - int numSegments = this.model.getHiddenStates().size(); - Map probabilities = new HashMap<>(); - Map previousSegments = new HashMap<>(); - Map> lapTimestamps = new HashMap<>(); - - for (int nextSegment = 0; nextSegment < numSegments; nextSegment++) { - probabilities.put(nextSegment, 0.0); - for (int previousSegment = 0; previousSegment < numSegments; previousSegment++) { - double probability = this.lastState.probabilities().get(previousSegment) * - this.model.getTransitionProbabilities().get(previousSegment).get(nextSegment) * - this.model.getEmitProbabilities().get(nextSegment).get(observation); - if (probabilities.get(nextSegment) < probability) { - probabilities.put(nextSegment, probability); - previousSegments.put(nextSegment, previousSegment); - - int half = numSegments / 2; - // Dit is het algoritme van De Voerstreek - int delta = half - (half - (nextSegment - previousSegment)) % numSegments; - - Set newTimestamps = new TreeSet<>(this.lastState.lapTimestamps().get(previousSegment)); - - if (delta > 0 && previousSegment > nextSegment) { - // forward wrap-around - newTimestamps.add(observationTimestamp); - } else if (delta < 0 && previousSegment < nextSegment) { - // backwards wrap-around - Optional highestTimestamp = newTimestamps.stream().max(Timestamp::compareTo); - highestTimestamp.ifPresent(newTimestamps::remove); - } - lapTimestamps.put(nextSegment, newTimestamps); - } - } - } - - // normalize probabilities - double sum = probabilities.values().stream().reduce(0.0, Double::sum); - for (int i = 0; i < numSegments; i++) { - probabilities.put(i, probabilities.get(i) / sum); - } - - this.lastState = new ViterbiState(probabilities, previousSegments, lapTimestamps); - } - - /** - * Get the current state of the Viterbi algorithm. - * @return The last Result. - */ - public ViterbiState getState() { - return this.lastState; - } -} diff --git a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiModel.java b/src/main/java/telraam/logic/viterbi/algorithm/ViterbiModel.java deleted file mode 100644 index edda291..0000000 --- a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiModel.java +++ /dev/null @@ -1,30 +0,0 @@ -package telraam.logic.viterbi.algorithm; - -import java.util.Map; -import java.util.Set; - -public record ViterbiModel(Set observations, Set hiddenStates, - Map> transitionProbabilities, - Map> emitProbabilities, - Map startProbabilities) { - - public Set getObservations() { - return observations; - } - - public Set getHiddenStates() { - return hiddenStates; - } - - public Map> getTransitionProbabilities() { - return transitionProbabilities; - } - - public Map> getEmitProbabilities() { - return emitProbabilities; - } - - public Map getStartProbabilities() { - return startProbabilities; - } -} diff --git a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiState.java b/src/main/java/telraam/logic/viterbi/algorithm/ViterbiState.java deleted file mode 100644 index ada5d6b..0000000 --- a/src/main/java/telraam/logic/viterbi/algorithm/ViterbiState.java +++ /dev/null @@ -1,25 +0,0 @@ -package telraam.logic.viterbi.algorithm; - -import java.sql.Timestamp; -import java.util.Map; -import java.util.Set; - -/** - * Helper class to store steps in the Viterbi algorithm. - */ -public record ViterbiState(Map probabilities, Map previousStates, Map> lapTimestamps) { - /** - * Get the most likely state to be in, in this Result - * - * @return The state that is most likely. - */ - public Integer mostLikelySegment() { - int mostLikelySegment = 0; - for (int i : probabilities.keySet()) { - if (this.probabilities.get(i) > this.probabilities.get(mostLikelySegment)) { - mostLikelySegment = i; - } - } - return mostLikelySegment; - } -} diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index cf371f8..54e04db 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -8,6 +8,8 @@ import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.logic.Lapper; +import telraam.station.models.RonnyDetection; +import telraam.station.models.RonnyResponse; import java.io.IOException; import java.net.ConnectException; diff --git a/src/main/java/telraam/station/RonnyDetection.java b/src/main/java/telraam/station/models/RonnyDetection.java similarity index 90% rename from src/main/java/telraam/station/RonnyDetection.java rename to src/main/java/telraam/station/models/RonnyDetection.java index 40689b8..234a50d 100644 --- a/src/main/java/telraam/station/RonnyDetection.java +++ b/src/main/java/telraam/station/models/RonnyDetection.java @@ -1,4 +1,4 @@ -package telraam.station; +package telraam.station.models; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/telraam/station/RonnyResponse.java b/src/main/java/telraam/station/models/RonnyResponse.java similarity index 87% rename from src/main/java/telraam/station/RonnyResponse.java rename to src/main/java/telraam/station/models/RonnyResponse.java index b2cf9ef..011f2c7 100644 --- a/src/main/java/telraam/station/RonnyResponse.java +++ b/src/main/java/telraam/station/models/RonnyResponse.java @@ -1,4 +1,4 @@ -package telraam.station; +package telraam.station.models; import java.util.List; diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt index f11cd06..46bfca7 100644 --- a/src/main/resources/banner.txt +++ b/src/main/resources/banner.txt @@ -1 +1,8 @@ -ZeusWPI - Telraam \ No newline at end of file + + + _____ __ ______ ___ _____ _ +|__ /___ _ _ ___ \ \ / / _ \_ _| |_ _|__| |_ __ __ _ __ _ _ __ ___ + / // _ \ | | / __| \ \ /\ / /| |_) | | _____ | |/ _ \ | '__/ _` |/ _` | '_ ` _ \ + / /| __/ |_| \__ \ \ V V / | __/| | |_____| | | __/ | | | (_| | (_| | | | | | | +/____\___|\__,_|___/ \_/\_/ |_| |___| |_|\___|_|_| \__,_|\__,_|_| |_| |_| + diff --git a/src/test/java/telraam/logic/SimpleLapperTest.java b/src/test/java/telraam/logic/SimpleLapperTest.java index 4214d13..7758c47 100644 --- a/src/test/java/telraam/logic/SimpleLapperTest.java +++ b/src/test/java/telraam/logic/SimpleLapperTest.java @@ -8,6 +8,7 @@ import telraam.database.models.Detection; import telraam.database.models.Lap; import telraam.database.models.LapSource; +import telraam.logic.simple.SimpleLapper; import java.sql.Timestamp; import java.util.Optional; From 57e998a8ff03b70cffada2e625d7d67f841b3605 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Mon, 25 Mar 2024 20:37:54 +0100 Subject: [PATCH 21/90] chore(BatonStatusHolder): go all-in on lazy-loading the baton statuses --- .../telraam/monitoring/BatonStatusHolder.java | 24 ------------------- 1 file changed, 24 deletions(-) diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java index e3e4f36..b791e0e 100644 --- a/src/main/java/telraam/monitoring/BatonStatusHolder.java +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -20,32 +20,12 @@ public class BatonStatusHolder { private BatonDAO batonDAO; private DetectionDAO detectionDAO; - private boolean initialized = false; public BatonStatusHolder(BatonDAO BDAO, DetectionDAO DDAO) { batonDAO = BDAO; detectionDAO = DDAO; } - private void initStatus() { - if (initialized) return; - initialized = true; - var batons = batonDAO.getAll(); - for (Baton baton : batons) { - BatonStatus batonStatus = new BatonStatus( - baton.getMac().toLowerCase(), - baton.getId(), - baton.getName(), - 0, - 0, - false, - null, - -1 - ); - batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); - } - } - private BatonStatus getStatusForBaton(String batonMac) { BatonStatus batonStatus = batonStatusMap.get(batonMac); if (batonStatus == null) { @@ -72,7 +52,6 @@ private BatonStatus getStatusForBaton(String batonMac) { } public List GetAllBatonStatuses() { - this.initStatus(); // For each baton, fetch latest detection var batons = batonDAO.getAll(); for (Baton baton : batons) { @@ -106,7 +85,6 @@ private void updateState(Detection msg) { } public BatonStatus GetBatonStatus(Integer batonId) { - this.initStatus(); if (!batonIdToMac.containsKey(batonId)) { var baton = batonDAO.getById(batonId); baton.ifPresent(value -> batonIdToMac.put(batonId, value.getMac().toLowerCase())); @@ -116,7 +94,6 @@ public BatonStatus GetBatonStatus(Integer batonId) { } public BatonStatus createBatonStatus(Integer batonId) { - this.initStatus(); String batonMac = batonIdToMac.get(batonId); if (batonMac != null) { return getStatusForBaton(batonMac); @@ -142,7 +119,6 @@ public BatonStatus createBatonStatus(Integer batonId) { } public void resetRebooted(int batonId) { - this.initStatus(); var batonStatus = GetBatonStatus(batonId); if (batonStatus == null) { return; From 98d3d55bdcca6dfa2f81d580845567390af55761 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 20:41:13 +0100 Subject: [PATCH 22/90] optimize imports & reformat --- src/main/java/telraam/App.java | 2 +- .../java/telraam/api/AcceptedLapsResource.java | 5 ----- src/main/java/telraam/api/BatonResource.java | 6 ++++-- .../telraam/api/BatonSwitchoverResource.java | 3 --- src/main/java/telraam/api/LapCountResource.java | 8 ++++---- .../telraam/api/LapSourceSwitchoverResource.java | 1 - .../java/telraam/api/MonitoringResource.java | 4 +++- src/main/java/telraam/api/TeamResource.java | 9 +++++---- src/main/java/telraam/api/TimeResource.java | 1 - src/main/java/telraam/database/daos/LapDAO.java | 2 -- .../telraam/database/models/BatonSwitchover.java | 3 ++- .../database/models/LapSourceSwitchover.java | 3 ++- .../java/telraam/database/models/Station.java | 16 ++++++++++++---- src/main/java/telraam/database/models/Team.java | 2 -- .../telraam/database/models/TeamLapCount.java | 2 -- src/main/java/telraam/logic/Lapper.java | 1 + .../telraam/logic/external/ExternalLapper.java | 2 +- .../java/telraam/logic/robust/RobustLapper.java | 16 +++++++++++----- .../java/telraam/logic/simple/SimpleLapper.java | 3 ++- .../monitoring/BatonDetectionManager.java | 2 +- .../monitoring/StationDetectionManager.java | 9 +++++---- .../monitoring/models/BatonDetection.java | 10 +++++++++- .../java/telraam/station/JsonBodyHandler.java | 4 ++-- .../telraam/station/models/RonnyResponse.java | 4 ++-- src/main/java/telraam/util/AcceptedLapsUtil.java | 4 ++-- 25 files changed, 69 insertions(+), 53 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 243edc8..12d7851 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -106,7 +106,7 @@ public void run(AppConfiguration configuration, Environment environment) throws // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); - if (! testing) { + if (!testing) { // Set up lapper algorithms Set lappers = new HashSet<>(); diff --git a/src/main/java/telraam/api/AcceptedLapsResource.java b/src/main/java/telraam/api/AcceptedLapsResource.java index 6b14dc4..135c984 100644 --- a/src/main/java/telraam/api/AcceptedLapsResource.java +++ b/src/main/java/telraam/api/AcceptedLapsResource.java @@ -2,18 +2,13 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import telraam.database.daos.LapDAO; -import telraam.database.daos.LapSourceSwitchoverDAO; import telraam.database.models.Lap; -import telraam.database.models.LapSourceSwitchover; import telraam.util.AcceptedLapsUtil; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.ArrayList; -import java.util.Comparator; import java.util.List; @Path("/accepted-laps") diff --git a/src/main/java/telraam/api/BatonResource.java b/src/main/java/telraam/api/BatonResource.java index a584432..ccf8e46 100644 --- a/src/main/java/telraam/api/BatonResource.java +++ b/src/main/java/telraam/api/BatonResource.java @@ -1,10 +1,12 @@ package telraam.api; -import io.swagger.annotations.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import telraam.database.daos.BatonDAO; import telraam.database.models.Baton; -import javax.ws.rs.*; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; diff --git a/src/main/java/telraam/api/BatonSwitchoverResource.java b/src/main/java/telraam/api/BatonSwitchoverResource.java index 6cc6611..f9f27f4 100644 --- a/src/main/java/telraam/api/BatonSwitchoverResource.java +++ b/src/main/java/telraam/api/BatonSwitchoverResource.java @@ -2,11 +2,8 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import telraam.database.daos.BatonDAO; import telraam.database.daos.BatonSwitchoverDAO; -import telraam.database.models.Baton; import telraam.database.models.BatonSwitchover; -import telraam.database.models.LapSourceSwitchover; import javax.ws.rs.Path; import javax.ws.rs.Produces; diff --git a/src/main/java/telraam/api/LapCountResource.java b/src/main/java/telraam/api/LapCountResource.java index c3a857d..b82be82 100644 --- a/src/main/java/telraam/api/LapCountResource.java +++ b/src/main/java/telraam/api/LapCountResource.java @@ -2,11 +2,8 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import telraam.database.daos.LapDAO; -import telraam.database.daos.LapSourceSwitchoverDAO; import telraam.database.daos.TeamDAO; import telraam.database.models.Lap; -import telraam.database.models.LapSourceSwitchover; import telraam.database.models.Team; import telraam.util.AcceptedLapsUtil; @@ -14,7 +11,9 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; @Path("/lap-counts") @Api("/lap-counts") @@ -25,6 +24,7 @@ public class LapCountResource { public LapCountResource(TeamDAO teamDAO) { this.teamDAO = teamDAO; } + @GET @ApiOperation("Get the current lap counts per team") public Map getLapCounts() { diff --git a/src/main/java/telraam/api/LapSourceSwitchoverResource.java b/src/main/java/telraam/api/LapSourceSwitchoverResource.java index 06290bf..cf07ef3 100644 --- a/src/main/java/telraam/api/LapSourceSwitchoverResource.java +++ b/src/main/java/telraam/api/LapSourceSwitchoverResource.java @@ -3,7 +3,6 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import telraam.database.daos.LapSourceSwitchoverDAO; -import telraam.database.models.LapSource; import telraam.database.models.LapSourceSwitchover; import javax.ws.rs.Path; diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java index 0a925ea..01bbd9b 100644 --- a/src/main/java/telraam/api/MonitoringResource.java +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -8,7 +8,9 @@ import telraam.database.models.LapSource; import telraam.database.models.Team; import telraam.database.models.TeamLapCount; -import telraam.monitoring.*; +import telraam.monitoring.BatonDetectionManager; +import telraam.monitoring.BatonStatusHolder; +import telraam.monitoring.StationDetectionManager; import telraam.monitoring.models.BatonDetection; import telraam.monitoring.models.BatonStatus; import telraam.monitoring.models.LapCountForTeam; diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 67c5b04..6a1ac54 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -22,6 +22,7 @@ @Produces(MediaType.APPLICATION_JSON) public class TeamResource extends AbstractListableResource { BatonSwitchoverDAO batonSwitchoverDAO; + public TeamResource(TeamDAO teamDAO, BatonSwitchoverDAO batonSwitchoverDAO) { super(teamDAO); this.batonSwitchoverDAO = batonSwitchoverDAO; @@ -67,10 +68,10 @@ public Team update(Team team, Optional id) { if (!Objects.equals(previousTeam.getBatonId(), team.getBatonId())) { this.batonSwitchoverDAO.insert(new BatonSwitchover( - team.getId(), - previousTeam.getBatonId(), - team.getBatonId(), - Timestamp.from(Instant.now()) + team.getId(), + previousTeam.getBatonId(), + team.getBatonId(), + Timestamp.from(Instant.now()) )); } diff --git a/src/main/java/telraam/api/TimeResource.java b/src/main/java/telraam/api/TimeResource.java index 0c85770..1abc075 100644 --- a/src/main/java/telraam/api/TimeResource.java +++ b/src/main/java/telraam/api/TimeResource.java @@ -7,7 +7,6 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.time.Instant; @Path("/time") @Api("/time") diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index 8c98785..f484f6f 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -10,11 +10,9 @@ import telraam.database.models.Lap; import telraam.database.models.TeamLapCount; - import java.sql.Timestamp; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Optional; public interface LapDAO extends DAO { diff --git a/src/main/java/telraam/database/models/BatonSwitchover.java b/src/main/java/telraam/database/models/BatonSwitchover.java index 67a024a..358446e 100644 --- a/src/main/java/telraam/database/models/BatonSwitchover.java +++ b/src/main/java/telraam/database/models/BatonSwitchover.java @@ -11,7 +11,8 @@ public class BatonSwitchover { private Timestamp timestamp; // DO NOT REMOVE - public BatonSwitchover() {} + public BatonSwitchover() { + } public BatonSwitchover(Integer teamId, Integer previousBatonId, Integer newBatonId, Timestamp timestamp) { this.teamId = teamId; diff --git a/src/main/java/telraam/database/models/LapSourceSwitchover.java b/src/main/java/telraam/database/models/LapSourceSwitchover.java index 6d645ca..ceef17d 100644 --- a/src/main/java/telraam/database/models/LapSourceSwitchover.java +++ b/src/main/java/telraam/database/models/LapSourceSwitchover.java @@ -9,7 +9,8 @@ public class LapSourceSwitchover { private Timestamp timestamp; // DO NOT REMOVE - public LapSourceSwitchover() {} + public LapSourceSwitchover() { + } public LapSourceSwitchover(Integer newLapSource, Timestamp timestamp) { this.newLapSource = newLapSource; diff --git a/src/main/java/telraam/database/models/Station.java b/src/main/java/telraam/database/models/Station.java index 4439b83..b84d338 100644 --- a/src/main/java/telraam/database/models/Station.java +++ b/src/main/java/telraam/database/models/Station.java @@ -10,7 +10,7 @@ public class Station { private Double coordY; public Station() { - this.isBroken = false; + this.isBroken = false; } public Station(String name, String url) { @@ -59,7 +59,9 @@ public Boolean getIsBroken() { return isBroken; } - public void setBroken(Boolean isBroken) { this.isBroken = isBroken; } + public void setBroken(Boolean isBroken) { + this.isBroken = isBroken; + } public String getUrl() { return this.url; @@ -69,13 +71,19 @@ public void setUrl(String url) { this.url = url; } - public Double getCoordX() { return this.coordX; }; + public Double getCoordX() { + return this.coordX; + } + + ; public void setCoordX(Double coordX) { this.coordX = coordX; } - public Double getCoordY() { return this.coordY; } + public Double getCoordY() { + return this.coordY; + } public void setCoordY(Double coordY) { this.coordY = coordY; diff --git a/src/main/java/telraam/database/models/Team.java b/src/main/java/telraam/database/models/Team.java index 1713d93..3ed784e 100644 --- a/src/main/java/telraam/database/models/Team.java +++ b/src/main/java/telraam/database/models/Team.java @@ -1,7 +1,5 @@ package telraam.database.models; -import telraam.database.daos.BatonSwitchoverDAO; - public class Team { private Integer id; private String name; diff --git a/src/main/java/telraam/database/models/TeamLapCount.java b/src/main/java/telraam/database/models/TeamLapCount.java index 96699a9..d7d3015 100644 --- a/src/main/java/telraam/database/models/TeamLapCount.java +++ b/src/main/java/telraam/database/models/TeamLapCount.java @@ -1,7 +1,5 @@ package telraam.database.models; -import com.fasterxml.jackson.annotation.JsonProperty; - public class TeamLapCount { private Integer lapSourceId; private Integer lapCount; diff --git a/src/main/java/telraam/logic/Lapper.java b/src/main/java/telraam/logic/Lapper.java index 995d067..c3dc674 100644 --- a/src/main/java/telraam/logic/Lapper.java +++ b/src/main/java/telraam/logic/Lapper.java @@ -5,5 +5,6 @@ public interface Lapper { void handle(Detection msg); + void registerAPI(JerseyEnvironment jersey); } diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index cd1158b..97d4962 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -37,7 +37,7 @@ public void handle(Detection msg) { } public void saveLaps(List teamLaps) { - List laps = lapDAO.getAllBySource(lapSourceId).stream().filter(l -> ! l.getManual()).toList(); + List laps = lapDAO.getAllBySource(lapSourceId).stream().filter(l -> !l.getManual()).toList(); // Remember laps we have to take actions on List lapsToDelete = new LinkedList<>(); diff --git a/src/main/java/telraam/logic/robust/RobustLapper.java b/src/main/java/telraam/logic/robust/RobustLapper.java index 07335c4..2ad64c5 100644 --- a/src/main/java/telraam/logic/robust/RobustLapper.java +++ b/src/main/java/telraam/logic/robust/RobustLapper.java @@ -2,8 +2,14 @@ import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.*; -import telraam.database.models.*; +import telraam.database.daos.DetectionDAO; +import telraam.database.daos.LapDAO; +import telraam.database.daos.LapSourceDAO; +import telraam.database.daos.StationDAO; +import telraam.database.models.Detection; +import telraam.database.models.Lap; +import telraam.database.models.LapSource; +import telraam.database.models.Station; import telraam.logic.Lapper; import java.sql.Timestamp; @@ -112,7 +118,7 @@ public void calculateLaps() { } else { // We're in a new interval, use the detection with the highest RSSI to update trajectory // Check if new station is more likely to be in front of the runner - if (! (backwardPathDistance(lastStationPosition, currentStationPosition) <= 3)) { + if (!(backwardPathDistance(lastStationPosition, currentStationPosition) <= 3)) { if (isStartBetween(lastStationPosition, currentStationPosition)) { // Add lap if we passed the start line lapTimes.add(detection.getTimestamp()); @@ -146,7 +152,7 @@ private boolean isStartBetween(int fromStation, int toStation) { private void save() { // Get all the old laps and sort by team List laps = lapDAO.getAllBySource(lapSourceId); - laps = laps.stream().filter(lap -> ! lap.getManual()).toList(); + laps = laps.stream().filter(lap -> !lap.getManual()).toList(); Map> oldLaps = new HashMap<>(); for (Integer teamId : teamLaps.keySet()) { @@ -169,7 +175,7 @@ private void save() { // Go over each lap and compare timestamp while (i < oldLapsTeam.size() && i < newLapsTeam.size()) { // Update the timestamp if it isn't equal - if (! oldLapsTeam.get(i).getTimestamp().equals(newLapsTeam.get(i).getTimestamp())) { + if (!oldLapsTeam.get(i).getTimestamp().equals(newLapsTeam.get(i).getTimestamp())) { oldLapsTeam.get(i).setTimestamp(newLapsTeam.get(i).getTimestamp()); lapsToUpdate.add(oldLapsTeam.get(i)); } diff --git a/src/main/java/telraam/logic/simple/SimpleLapper.java b/src/main/java/telraam/logic/simple/SimpleLapper.java index 6acc326..15c1265 100644 --- a/src/main/java/telraam/logic/simple/SimpleLapper.java +++ b/src/main/java/telraam/logic/simple/SimpleLapper.java @@ -67,7 +67,8 @@ public void handle(Detection msg) { } @Override - public void registerAPI(JerseyEnvironment jersey) {} + public void registerAPI(JerseyEnvironment jersey) { + } private void generateLap(List detections) { Detection first = detections.get(0); diff --git a/src/main/java/telraam/monitoring/BatonDetectionManager.java b/src/main/java/telraam/monitoring/BatonDetectionManager.java index 917e5db..db6b10b 100644 --- a/src/main/java/telraam/monitoring/BatonDetectionManager.java +++ b/src/main/java/telraam/monitoring/BatonDetectionManager.java @@ -60,7 +60,7 @@ public Map> getBatonDetections() { } var batonDetections = batonDetectionMap.get(batonId); var team = teamMap.get(batonTeamMap.get(batonId)); - var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(),d.getStationId(), batonId, team.getName()); + var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), d.getStationId(), batonId, team.getName()); batonDetections.add(batonDetection); }); return batonDetectionMap; diff --git a/src/main/java/telraam/monitoring/StationDetectionManager.java b/src/main/java/telraam/monitoring/StationDetectionManager.java index aca26da..3929f42 100644 --- a/src/main/java/telraam/monitoring/StationDetectionManager.java +++ b/src/main/java/telraam/monitoring/StationDetectionManager.java @@ -2,12 +2,13 @@ import telraam.database.daos.DetectionDAO; import telraam.database.daos.StationDAO; -import telraam.database.daos.TeamDAO; import telraam.database.models.Detection; import telraam.database.models.Station; -import java.util.*; -import java.util.stream.Collectors; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; public class StationDetectionManager { private DetectionDAO detectionDAO; @@ -27,7 +28,7 @@ public Map timeSinceLastDetectionPerStation() { Optional maybeStation = this.stationDAO.getById(stationId); if (maybeDetection.isPresent() && maybeStation.isPresent()) { Long time = maybeDetection.get().getTimestamp().getTime(); - stationIdToTimeSinceLatestDetection.put(maybeStation.get().getName(), (System.currentTimeMillis() - time)/1000); + stationIdToTimeSinceLatestDetection.put(maybeStation.get().getName(), (System.currentTimeMillis() - time) / 1000); } } return stationIdToTimeSinceLatestDetection; diff --git a/src/main/java/telraam/monitoring/models/BatonDetection.java b/src/main/java/telraam/monitoring/models/BatonDetection.java index 38f97d9..646bf34 100644 --- a/src/main/java/telraam/monitoring/models/BatonDetection.java +++ b/src/main/java/telraam/monitoring/models/BatonDetection.java @@ -1,7 +1,6 @@ package telraam.monitoring.models; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.models.auth.In; public class BatonDetection { @JsonProperty("detected_time") @@ -26,30 +25,39 @@ public BatonDetection(Integer detectionTime, Integer rssi, Integer stationId, In public Integer getDetectionTime() { return detectionTime; } + public void setDetectionTime(Integer detectionTime) { this.detectionTime = detectionTime; } + public Integer getRssi() { return rssi; } + public void setRssi(Integer rssi) { this.rssi = rssi; } + public Integer getTeamId() { return teamId; } + public void setTeamId(Integer teamId) { this.teamId = teamId; } + public Integer getStationId() { return stationId; } + public void setStationId(Integer stationId) { this.stationId = stationId; } + public String getTeamName() { return teamName; } + public void setTeamName(String teamName) { this.teamName = teamName; } diff --git a/src/main/java/telraam/station/JsonBodyHandler.java b/src/main/java/telraam/station/JsonBodyHandler.java index f9ddd04..2d28e7f 100644 --- a/src/main/java/telraam/station/JsonBodyHandler.java +++ b/src/main/java/telraam/station/JsonBodyHandler.java @@ -27,8 +27,8 @@ public static HttpResponse.BodySubscriber> asJSON(Class targe HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream(); return HttpResponse.BodySubscribers.mapping( - upstream, - inputStream -> toSupplierOfType(inputStream, targetType)); + upstream, + inputStream -> toSupplierOfType(inputStream, targetType)); } public static Supplier toSupplierOfType(InputStream inputStream, Class targetType) { diff --git a/src/main/java/telraam/station/models/RonnyResponse.java b/src/main/java/telraam/station/models/RonnyResponse.java index 011f2c7..726cafc 100644 --- a/src/main/java/telraam/station/models/RonnyResponse.java +++ b/src/main/java/telraam/station/models/RonnyResponse.java @@ -1,9 +1,9 @@ package telraam.station.models; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + public class RonnyResponse { public List detections; diff --git a/src/main/java/telraam/util/AcceptedLapsUtil.java b/src/main/java/telraam/util/AcceptedLapsUtil.java index f6cac0a..c0f747b 100644 --- a/src/main/java/telraam/util/AcceptedLapsUtil.java +++ b/src/main/java/telraam/util/AcceptedLapsUtil.java @@ -23,8 +23,8 @@ public AcceptedLapsUtil(LapDAO lapDAO, LapSourceSwitchoverDAO lapSourceSwitchove public static void createInstance(Jdbi jdbi) { instance = new AcceptedLapsUtil( - jdbi.onDemand(LapDAO.class), - jdbi.onDemand(LapSourceSwitchoverDAO.class) + jdbi.onDemand(LapDAO.class), + jdbi.onDemand(LapSourceSwitchoverDAO.class) ); } From 514c34cd746443479159bd7fa16c874ea33ca1a0 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 20:47:24 +0100 Subject: [PATCH 23/90] restructure external lapper --- src/main/java/telraam/logic/external/ExternalLapper.java | 1 + .../java/telraam/logic/external/ExternalLapperResource.java | 2 ++ .../telraam/logic/external/{ => models}/ExternalLapperLap.java | 2 +- .../logic/external/{ => models}/ExternalLapperStats.java | 2 +- .../logic/external/{ => models}/ExternalLapperTeamLaps.java | 2 +- 5 files changed, 6 insertions(+), 3 deletions(-) rename src/main/java/telraam/logic/external/{ => models}/ExternalLapperLap.java (62%) rename src/main/java/telraam/logic/external/{ => models}/ExternalLapperStats.java (95%) rename src/main/java/telraam/logic/external/{ => models}/ExternalLapperTeamLaps.java (76%) diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index 97d4962..d2e7e34 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -8,6 +8,7 @@ import telraam.database.models.Lap; import telraam.database.models.LapSource; import telraam.logic.Lapper; +import telraam.logic.external.models.ExternalLapperTeamLaps; import java.sql.Timestamp; import java.util.Comparator; diff --git a/src/main/java/telraam/logic/external/ExternalLapperResource.java b/src/main/java/telraam/logic/external/ExternalLapperResource.java index 07d9ef5..d640f6b 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperResource.java +++ b/src/main/java/telraam/logic/external/ExternalLapperResource.java @@ -2,6 +2,8 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import telraam.logic.external.models.ExternalLapperStats; +import telraam.logic.external.models.ExternalLapperTeamLaps; import javax.ws.rs.GET; import javax.ws.rs.POST; diff --git a/src/main/java/telraam/logic/external/ExternalLapperLap.java b/src/main/java/telraam/logic/external/models/ExternalLapperLap.java similarity index 62% rename from src/main/java/telraam/logic/external/ExternalLapperLap.java rename to src/main/java/telraam/logic/external/models/ExternalLapperLap.java index d694994..724ec5f 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperLap.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperLap.java @@ -1,4 +1,4 @@ -package telraam.logic.external; +package telraam.logic.external.models; public class ExternalLapperLap { public double timestamp; diff --git a/src/main/java/telraam/logic/external/ExternalLapperStats.java b/src/main/java/telraam/logic/external/models/ExternalLapperStats.java similarity index 95% rename from src/main/java/telraam/logic/external/ExternalLapperStats.java rename to src/main/java/telraam/logic/external/models/ExternalLapperStats.java index 9910898..74598d3 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperStats.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperStats.java @@ -1,4 +1,4 @@ -package telraam.logic.external; +package telraam.logic.external.models; import java.util.List; diff --git a/src/main/java/telraam/logic/external/ExternalLapperTeamLaps.java b/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java similarity index 76% rename from src/main/java/telraam/logic/external/ExternalLapperTeamLaps.java rename to src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java index a003f3f..c184222 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperTeamLaps.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java @@ -1,4 +1,4 @@ -package telraam.logic.external; +package telraam.logic.external.models; import java.util.List; From 8ba54fd6368bbb962c12c6f04dbc9552caf82723 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 21:22:44 +0100 Subject: [PATCH 24/90] update workflow --- .github/workflows/gradle.yml | 24 +++++++++---------- .../logic/{ => simple}/SimpleLapperTest.java | 3 ++- 2 files changed, 13 insertions(+), 14 deletions(-) rename src/test/java/telraam/logic/{ => simple}/SimpleLapperTest.java (97%) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 40e55a9..c9a2b1b 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -16,26 +16,24 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up JDK 16 + + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 16 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar + java-version: 17 + - name: Cache Gradle packages uses: actions/cache@v1 with: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} restore-keys: ${{ runner.os }}-gradle + - name: Grant execute permission for gradlew run: chmod +x gradlew - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: ./gradlew build sonarqube --info + + - name: Build + run: ./gradlew build + + - name: Build + run: ./gradlew test diff --git a/src/test/java/telraam/logic/SimpleLapperTest.java b/src/test/java/telraam/logic/simple/SimpleLapperTest.java similarity index 97% rename from src/test/java/telraam/logic/SimpleLapperTest.java rename to src/test/java/telraam/logic/simple/SimpleLapperTest.java index 7758c47..838397f 100644 --- a/src/test/java/telraam/logic/SimpleLapperTest.java +++ b/src/test/java/telraam/logic/simple/SimpleLapperTest.java @@ -1,4 +1,4 @@ -package telraam.logic; +package telraam.logic.simple; import org.jdbi.v3.core.Jdbi; import org.junit.jupiter.api.BeforeEach; @@ -8,6 +8,7 @@ import telraam.database.models.Detection; import telraam.database.models.Lap; import telraam.database.models.LapSource; +import telraam.logic.Lapper; import telraam.logic.simple.SimpleLapper; import java.sql.Timestamp; From d105b63cbed7d65e5978c7bef64f228d2670937a Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 21:29:48 +0100 Subject: [PATCH 25/90] remove sonarqube --- .github/workflows/gradle.yml | 2 +- build.gradle | 44 ------------------------------------ 2 files changed, 1 insertion(+), 45 deletions(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index c9a2b1b..d4fe08a 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -35,5 +35,5 @@ jobs: - name: Build run: ./gradlew build - - name: Build + - name: Test run: ./gradlew test diff --git a/build.gradle b/build.gradle index 5269053..dd78f2d 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,6 @@ import org.flywaydb.gradle.task.FlywayMigrateTask plugins { id 'java' id 'application' - id 'jacoco' - id 'org.sonarqube' version "3.0" id 'idea' id 'org.flywaydb.flyway' version "8.0.0" } @@ -88,42 +86,7 @@ test { jacocoTestReport } } -jacoco { - toolVersion = "0.8.7" - reportsDirectory = layout.buildDirectory.dir('coverage').get() -} -jacocoTestReport { - dependsOn { - test - } - reports { - xml.required = true - } - afterEvaluate { - classDirectories.setFrom files(classDirectories.files.collect { - fileTree(dir: it, exclude: [ - '**/database/models/**' - ]) - }) - } -} -jacocoTestCoverageVerification { - afterEvaluate { - classDirectories.setFrom files(classDirectories.files.collect { - fileTree(dir: it, exclude: [ - '**/database/models/**' - ]) - }) - } - violationRules { - rule { - limit { - minimum = 0.7 - } - } - } -} def prodProps = new Properties() file("$rootProject.projectDir/src/main/resources/telraam/prodConfig.properties").withInputStream { prodProps.load(it) @@ -150,10 +113,3 @@ task migrateTestingDatabase(type: FlywayMigrateTask) { url = testProps.getProperty("DB_URL") baselineOnMigrate = true } -sonarqube { - properties { - property "sonar.projectKey", "12urenloop_Telraam" - property "sonar.organization", "12urenloop" - property "sonar.host.url", "https://sonarcloud.io" - } -} From 991c8f398be702f5031cbfc3ad92461e721651f5 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 21:36:15 +0100 Subject: [PATCH 26/90] forgot a reference --- build.gradle | 3 --- 1 file changed, 3 deletions(-) diff --git a/build.gradle b/build.gradle index dd78f2d..d1a3b42 100644 --- a/build.gradle +++ b/build.gradle @@ -82,9 +82,6 @@ test { testLogging { events "passed", "skipped", "failed" } - finalizedBy { - jacocoTestReport - } } def prodProps = new Properties() From 6670b8aac0f688e0961e6e2e2a2afb6872a29b7d Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Mon, 25 Mar 2024 21:43:08 +0100 Subject: [PATCH 27/90] different gradle commands --- .github/workflows/gradle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index d4fe08a..f45a655 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -33,7 +33,7 @@ jobs: run: chmod +x gradlew - name: Build - run: ./gradlew build + run: ./gradlew compileJava compileTestJava - name: Test run: ./gradlew test From 25ae5ccb0d5b9154bdaf3050d5484fb763313e81 Mon Sep 17 00:00:00 2001 From: Jan Lecoutere Date: Thu, 28 Mar 2024 13:02:46 +0100 Subject: [PATCH 28/90] feat: introduce lombok to models (#117) * feat: introduce lombok to models * fix test with Station.setBroken -> Station.setIsBroken * feat: fix test locally --------- Co-authored-by: FKD13 <44001949+FKD13@users.noreply.github.com> --- build.gradle | 7 ++ .../telraam/database/daos/StationDAO.java | 4 +- .../java/telraam/database/models/Baton.java | 33 ++----- .../database/models/BatonSwitchover.java | 49 ++--------- .../telraam/database/models/Detection.java | 88 ++----------------- .../java/telraam/database/models/Lap.java | 48 ++-------- .../telraam/database/models/LapSource.java | 25 ++---- .../database/models/LapSourceSwitchover.java | 33 ++----- .../java/telraam/database/models/Station.java | 73 +++------------ .../java/telraam/database/models/Team.java | 32 ++----- .../telraam/database/models/TeamLapCount.java | 30 ++----- .../telraam/logic/simple/SimpleLapper.java | 2 +- .../telraam/database/daos/StationDAOTest.java | 6 +- 13 files changed, 65 insertions(+), 365 deletions(-) diff --git a/build.gradle b/build.gradle index d1a3b42..db65596 100644 --- a/build.gradle +++ b/build.gradle @@ -74,6 +74,13 @@ dependencies { // Swagger-UI implementation 'com.smoketurner:dropwizard-swagger:2.0.0-1' + + // Getter & Setter via annotations + compileOnly 'org.projectlombok:lombok:1.18.32' + annotationProcessor 'org.projectlombok:lombok:1.18.32' + + testCompileOnly 'org.projectlombok:lombok:1.18.32' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.32' } test { diff --git a/src/main/java/telraam/database/daos/StationDAO.java b/src/main/java/telraam/database/daos/StationDAO.java index cd73051..983eecf 100644 --- a/src/main/java/telraam/database/daos/StationDAO.java +++ b/src/main/java/telraam/database/daos/StationDAO.java @@ -19,7 +19,7 @@ public interface StationDAO extends DAO { List getAll(); @Override - @SqlUpdate("INSERT INTO station (name, distance_from_start, broken, url, coord_x, coord_y) VALUES (:name, :distanceFromStart, :isBroken, :url, :coordX, :coordY)") + @SqlUpdate("INSERT INTO station (name, distance_from_start, broken, url, coord_x, coord_y) VALUES (:name, :distanceFromStart, :broken, :url, :coordX, :coordY)") @GetGeneratedKeys({"id"}) int insert(@BindBean Station station); @@ -33,6 +33,6 @@ public interface StationDAO extends DAO { int deleteById(@Bind("id") int id); @Override - @SqlUpdate("UPDATE station SET name = :name, distance_from_start = :distanceFromStart, broken = :isBroken, url = :url, coord_x = :coordX, coord_y = :coordY WHERE id = :id") + @SqlUpdate("UPDATE station SET name = :name, distance_from_start = :distanceFromStart, broken = :broken, url = :url, coord_x = :coordX, coord_y = :coordY WHERE id = :id") int update(@Bind("id") int id, @BindBean Station station); } diff --git a/src/main/java/telraam/database/models/Baton.java b/src/main/java/telraam/database/models/Baton.java index 525b95b..f5889c0 100644 --- a/src/main/java/telraam/database/models/Baton.java +++ b/src/main/java/telraam/database/models/Baton.java @@ -1,16 +1,17 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.util.Objects; +@Getter @Setter @NoArgsConstructor public class Baton { private Integer id; private String name; private String mac; - // DO NOT REMOVE - public Baton() { - } - public Baton(String name) { this.name = name; } @@ -20,30 +21,6 @@ public Baton(String name, String mac) { this.mac = mac; } - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/telraam/database/models/BatonSwitchover.java b/src/main/java/telraam/database/models/BatonSwitchover.java index 358446e..d888870 100644 --- a/src/main/java/telraam/database/models/BatonSwitchover.java +++ b/src/main/java/telraam/database/models/BatonSwitchover.java @@ -1,8 +1,13 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.sql.Timestamp; import java.util.Objects; +@Getter @Setter @NoArgsConstructor public class BatonSwitchover { private Integer id; private Integer teamId; @@ -10,10 +15,6 @@ public class BatonSwitchover { private Integer newBatonId; private Timestamp timestamp; - // DO NOT REMOVE - public BatonSwitchover() { - } - public BatonSwitchover(Integer teamId, Integer previousBatonId, Integer newBatonId, Timestamp timestamp) { this.teamId = teamId; this.previousBatonId = previousBatonId; @@ -21,46 +22,6 @@ public BatonSwitchover(Integer teamId, Integer previousBatonId, Integer newBaton this.timestamp = timestamp; } - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getTeamId() { - return teamId; - } - - public void setTeamId(Integer teamId) { - this.teamId = teamId; - } - - public Integer getPreviousBatonId() { - return previousBatonId; - } - - public void setPreviousBatonId(Integer previousBatonId) { - this.previousBatonId = previousBatonId; - } - - public Integer getNewBatonId() { - return newBatonId; - } - - public void setNewBatonId(Integer newBatonId) { - this.newBatonId = newBatonId; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/telraam/database/models/Detection.java b/src/main/java/telraam/database/models/Detection.java index 6a7c916..23a4067 100644 --- a/src/main/java/telraam/database/models/Detection.java +++ b/src/main/java/telraam/database/models/Detection.java @@ -1,7 +1,12 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.sql.Timestamp; +@Setter @Getter @NoArgsConstructor public class Detection { private Integer id; private Integer batonId; @@ -14,9 +19,6 @@ public class Detection { private Timestamp timestampIngestion; private Integer teamId; - public Detection() { - } - public Detection(Integer batonId, Integer stationId, Integer rssi, Float battery, Long uptimeMs, Integer remoteId, Timestamp timestamp, Timestamp timestampIngestion) { this.batonId = batonId; this.stationId = stationId; @@ -27,84 +29,4 @@ public Detection(Integer batonId, Integer stationId, Integer rssi, Float battery this.timestamp = timestamp; this.timestampIngestion = timestampIngestion; } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getBatonId() { - return batonId; - } - - public void setBatonId(Integer batonId) { - this.batonId = batonId; - } - - public Integer getStationId() { - return stationId; - } - - public void setStationId(Integer stationId) { - this.stationId = stationId; - } - - public Integer getRssi() { - return rssi; - } - - public void setRssi(Integer rssi) { - this.rssi = rssi; - } - - public Float getBattery() { - return battery; - } - - public void setBattery(Float battery) { - this.battery = battery; - } - - public Long getUptimeMs() { - return uptimeMs; - } - - public void setUptimeMs(Long uptimeMs) { - this.uptimeMs = uptimeMs; - } - - public Integer getRemoteId() { - return remoteId; - } - - public void setRemoteId(Integer remoteId) { - this.remoteId = remoteId; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - - public Timestamp getTimestampIngestion() { - return timestampIngestion; - } - - public void setTimestampIngestion(Timestamp timestampIngestion) { - this.timestampIngestion = timestampIngestion; - } - - public Integer getTeamId() { - return teamId; - } - - public void setTeamId(Integer teamId) { - this.teamId = teamId; - } } diff --git a/src/main/java/telraam/database/models/Lap.java b/src/main/java/telraam/database/models/Lap.java index f084c9c..7573562 100644 --- a/src/main/java/telraam/database/models/Lap.java +++ b/src/main/java/telraam/database/models/Lap.java @@ -1,7 +1,12 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.sql.Timestamp; +@Getter @Setter @NoArgsConstructor public class Lap { private Integer id; private Integer teamId; @@ -10,52 +15,9 @@ public class Lap { private Boolean manual; private Timestamp timestamp; - public Lap() { - } - public Lap(Integer teamId, Integer lapSourceId, Timestamp timestamp) { this.teamId = teamId; this.lapSourceId = lapSourceId; this.timestamp = timestamp; } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getTeamId() { - return teamId; - } - - public void setTeamId(Integer teamId) { - this.teamId = teamId; - } - - public Integer getLapSourceId() { - return lapSourceId; - } - - public void setLapSourceId(Integer lapSourceId) { - this.lapSourceId = lapSourceId; - } - - public Boolean getManual() { - return manual; - } - - public void setManual(Boolean manual) { - this.manual = manual; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } } diff --git a/src/main/java/telraam/database/models/LapSource.java b/src/main/java/telraam/database/models/LapSource.java index 82ff02f..aa39fa3 100644 --- a/src/main/java/telraam/database/models/LapSource.java +++ b/src/main/java/telraam/database/models/LapSource.java @@ -1,33 +1,18 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + /** * The lap source tells you where the lap comes from. */ +@Getter @Setter @NoArgsConstructor public class LapSource { private Integer id; private String name; - public LapSource() { - - } - public LapSource(String name) { this.name = name; } - - public Integer getId() { - return id; - } - - public String getName() { - return name; - } - - public void setId(Integer id) { - this.id = id; - } - - public void setName(String name) { - this.name = name; - } } diff --git a/src/main/java/telraam/database/models/LapSourceSwitchover.java b/src/main/java/telraam/database/models/LapSourceSwitchover.java index ceef17d..4b3a445 100644 --- a/src/main/java/telraam/database/models/LapSourceSwitchover.java +++ b/src/main/java/telraam/database/models/LapSourceSwitchover.java @@ -1,46 +1,23 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.sql.Timestamp; import java.util.Objects; +@Getter @Setter @NoArgsConstructor public class LapSourceSwitchover { private Integer id; private Integer newLapSource; private Timestamp timestamp; - // DO NOT REMOVE - public LapSourceSwitchover() { - } - public LapSourceSwitchover(Integer newLapSource, Timestamp timestamp) { this.newLapSource = newLapSource; this.timestamp = timestamp; } - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getNewLapSource() { - return newLapSource; - } - - public void setNewLapSource(Integer newLapSource) { - this.newLapSource = newLapSource; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/telraam/database/models/Station.java b/src/main/java/telraam/database/models/Station.java index b84d338..442e412 100644 --- a/src/main/java/telraam/database/models/Station.java +++ b/src/main/java/telraam/database/models/Station.java @@ -1,91 +1,38 @@ package telraam.database.models; +import lombok.Getter; +import lombok.Setter; + +@Getter @Setter public class Station { private Integer id; private String name; private Double distanceFromStart; - private Boolean isBroken; + @Getter @Setter + private Boolean broken; private String url; private Double coordX; private Double coordY; public Station() { - this.isBroken = false; + this.broken = false; } public Station(String name, String url) { this.name = name; - this.isBroken = false; + this.broken = false; this.url = url; } public Station(String name, Double distanceFromStart, String url) { this.name = name; - this.isBroken = false; + this.broken = false; this.distanceFromStart = distanceFromStart; this.url = url; } public Station(String name, boolean isBroken) { this.name = name; - this.isBroken = isBroken; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Double getDistanceFromStart() { - return distanceFromStart; - } - - public void setDistanceFromStart(Double distanceFromStart) { - this.distanceFromStart = distanceFromStart; - } - - public Boolean getIsBroken() { - return isBroken; - } - - public void setBroken(Boolean isBroken) { - this.isBroken = isBroken; - } - - public String getUrl() { - return this.url; - } - - public void setUrl(String url) { - this.url = url; - } - - public Double getCoordX() { - return this.coordX; - } - - ; - - public void setCoordX(Double coordX) { - this.coordX = coordX; - } - - public Double getCoordY() { - return this.coordY; - } - - public void setCoordY(Double coordY) { - this.coordY = coordY; + this.broken = isBroken; } } diff --git a/src/main/java/telraam/database/models/Team.java b/src/main/java/telraam/database/models/Team.java index 3ed784e..94db208 100644 --- a/src/main/java/telraam/database/models/Team.java +++ b/src/main/java/telraam/database/models/Team.java @@ -1,13 +1,15 @@ package telraam.database.models; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter @Setter @NoArgsConstructor public class Team { private Integer id; private String name; private Integer batonId; - public Team() { - } - public Team(String name) { this.name = name; } @@ -16,28 +18,4 @@ public Team(String name, int batonId) { this.name = name; this.batonId = batonId; } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getBatonId() { - return batonId; - } - - public void setBatonId(Integer batonId) { - this.batonId = batonId; - } } diff --git a/src/main/java/telraam/database/models/TeamLapCount.java b/src/main/java/telraam/database/models/TeamLapCount.java index d7d3015..797c659 100644 --- a/src/main/java/telraam/database/models/TeamLapCount.java +++ b/src/main/java/telraam/database/models/TeamLapCount.java @@ -1,30 +1,12 @@ package telraam.database.models; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter @Setter @NoArgsConstructor @AllArgsConstructor public class TeamLapCount { private Integer lapSourceId; private Integer lapCount; - - public TeamLapCount() { - } - - public TeamLapCount(Integer lapTeamId, Integer lapCount) { - this.lapSourceId = lapTeamId; - this.lapCount = lapCount; - } - - public Integer getLapSourceId() { - return lapSourceId; - } - - public void setLapSourceId(Integer lapSourceId) { - this.lapSourceId = lapSourceId; - } - - public Integer getLapCount() { - return lapCount; - } - - public void setLapCount(Integer lapCount) { - this.lapCount = lapCount; - } } diff --git a/src/main/java/telraam/logic/simple/SimpleLapper.java b/src/main/java/telraam/logic/simple/SimpleLapper.java index 15c1265..9b26f9b 100644 --- a/src/main/java/telraam/logic/simple/SimpleLapper.java +++ b/src/main/java/telraam/logic/simple/SimpleLapper.java @@ -14,7 +14,7 @@ public class SimpleLapper implements Lapper { // Needs to be the same as in the lap_source database table. - static final String SOURCE_NAME = "simple-lapper"; + public static final String SOURCE_NAME = "simple-lapper"; private static final int MAX_SPEED = 50; private final LapSource source; diff --git a/src/test/java/telraam/database/daos/StationDAOTest.java b/src/test/java/telraam/database/daos/StationDAOTest.java index 64dceca..2bd64bc 100644 --- a/src/test/java/telraam/database/daos/StationDAOTest.java +++ b/src/test/java/telraam/database/daos/StationDAOTest.java @@ -34,7 +34,7 @@ void createStation() { Station station = stationOptional.get(); assertEquals("teststation", station.getName()); assertEquals(1d, station.getDistanceFromStart()); - assertEquals(false, station.getIsBroken()); + assertEquals(false, station.getBroken()); assertEquals("localhost:8000", station.getUrl()); } @@ -83,6 +83,7 @@ void testUpdateDoesUpdate() { testStation.setId(testid); testStation.setName("postUpdate"); testStation.setDistanceFromStart(2d); + testStation.setCoordY(0.69); testStation.setBroken(true); testStation.setUrl("localhost:8001"); int updatedRows = stationDAO.update(testid, testStation); @@ -92,7 +93,8 @@ void testUpdateDoesUpdate() { assertFalse(dbStation.isEmpty()); assertEquals("postUpdate", dbStation.get().getName()); assertEquals(2d, dbStation.get().getDistanceFromStart()); - assertEquals(true, dbStation.get().getIsBroken()); + assertEquals(true, dbStation.get().getBroken()); + assertEquals(0.69, dbStation.get().getCoordY()); assertEquals("localhost:8001", dbStation.get().getUrl()); } From 8f9e453b45ec68113cf20674657bf9677e6ecdc0 Mon Sep 17 00:00:00 2001 From: Jan Lecoutere Date: Thu, 28 Mar 2024 16:24:34 +0100 Subject: [PATCH 29/90] feat: update dependencies (#116) * feat: update dependencies * feat re-add swagger grouping + fix gradle file * fix(gradle): imagine following the same version scheme as their framework packages * add flyway postgres dependency --------- Co-authored-by: FKD13 <44001949+FKD13@users.noreply.github.com> --- build.gradle | 44 +-- gradle/wrapper/gradle-wrapper.jar | Bin 59203 -> 43462 bytes gradle/wrapper/gradle-wrapper.properties | 4 +- gradlew | 282 +++++++++++------- gradlew.bat | 35 ++- settings.gradle | 1 - src/main/java/telraam/App.java | 10 +- src/main/java/telraam/AppConfiguration.java | 7 +- .../java/telraam/api/AbstractResource.java | 36 ++- .../telraam/api/AcceptedLapsResource.java | 16 +- src/main/java/telraam/api/BatonResource.java | 22 +- .../telraam/api/BatonSwitchoverResource.java | 18 +- .../java/telraam/api/DetectionResource.java | 22 +- .../java/telraam/api/LapCountResource.java | 14 +- src/main/java/telraam/api/LapResource.java | 23 +- .../java/telraam/api/LapSourceResource.java | 21 +- .../api/LapSourceSwitchoverResource.java | 17 +- .../java/telraam/api/ListableResource.java | 2 +- .../java/telraam/api/MonitoringResource.java | 23 +- src/main/java/telraam/api/Resource.java | 5 +- .../java/telraam/api/StationResource.java | 22 +- src/main/java/telraam/api/TeamResource.java | 22 +- src/main/java/telraam/api/TimeResource.java | 17 +- .../external/ExternalLapperResource.java | 17 +- src/test/java/telraam/DatabaseTest.java | 3 +- .../java/telraam/api/BatonResourceTest.java | 2 +- 26 files changed, 374 insertions(+), 311 deletions(-) diff --git a/build.gradle b/build.gradle index db65596..1d4df44 100644 --- a/build.gradle +++ b/build.gradle @@ -1,20 +1,26 @@ import org.flywaydb.gradle.task.FlywayMigrateTask +buildscript { + dependencies { + classpath("org.flywaydb:flyway-database-postgresql:10.10.0") + } +} + plugins { id 'java' id 'application' id 'idea' - id 'org.flywaydb.flyway' version "8.0.0" + id 'org.flywaydb.flyway' version "10.0.0" } group 'telraam' version '1.0-SNAPSHOT' -sourceCompatibility = 16 +sourceCompatibility = 17 // Set our project variables project.ext { - dropwizardVersion = '2.0.25' + dropwizardVersion = '4.0.5' } repositories { @@ -24,7 +30,7 @@ application { mainClass.set('telraam.App') } -task runDev { +tasks.register('runDev') { finalizedBy { run.environment("CONFIG_KEY", "DEVELOPMENT") @@ -32,7 +38,7 @@ task runDev { run } } -task runProd { +tasks.register('runProd') { finalizedBy { run.environment("CONFIG_KEY", "PRODUCTION") @@ -45,7 +51,9 @@ idea { inheritOutputDirs = true } } -build.finalizedBy(javadoc) +build { + finalizedBy(javadoc) +} dependencies { // Web framework stuff @@ -56,24 +64,24 @@ dependencies { 'io.dropwizard:dropwizard-jdbi3:' + dropwizardVersion, ) // Database - implementation('com.h2database:h2:1.4.200') - implementation('org.postgresql:postgresql:42.2.24.jre7') + implementation('com.h2database:h2:2.2.220') + implementation('org.postgresql:postgresql:42.7.3') // Testing - testImplementation('org.junit.jupiter:junit-jupiter:5.8.1') - testImplementation('org.flywaydb:flyway-core:7.14.1') - testImplementation('org.mockito:mockito-core:3.12.4') + testImplementation('org.junit.jupiter:junit-jupiter:5.10.2') + testImplementation('org.flywaydb:flyway-core:10.10.0') + testImplementation('org.mockito:mockito-core:5.11.0') testImplementation("io.dropwizard:dropwizard-testing:" + dropwizardVersion) // Statistics for Viterbi-lapper - implementation("org.apache.commons:commons-math3:3.0") + implementation("org.apache.commons:commons-math3:3.6.1") // JAX-B dependencies for JDK 9+ -> https://stackoverflow.com/a/43574427 - implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359' - implementation 'org.glassfish.jaxb:jaxb-runtime:3.0.1' + implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.2' + implementation 'org.glassfish.jaxb:jaxb-runtime:4.0.5' // Swagger-UI - implementation 'com.smoketurner:dropwizard-swagger:2.0.0-1' + implementation('com.smoketurner:dropwizard-swagger:4.0.5-1') // Getter & Setter via annotations compileOnly 'org.projectlombok:lombok:1.18.32' @@ -95,7 +103,7 @@ def prodProps = new Properties() file("$rootProject.projectDir/src/main/resources/telraam/prodConfig.properties").withInputStream { prodProps.load(it) } -task migrateProductionDatabase(type: FlywayMigrateTask) { +tasks.register('migrateProductionDatabase', FlywayMigrateTask) { url = prodProps.getProperty("DB_URL") } @@ -103,7 +111,7 @@ def devProps = new Properties() file("$rootProject.projectDir/src/main/resources/telraam/devConfig.properties").withInputStream { devProps.load(it) } -task migrateDevelopmentDatabase(type: FlywayMigrateTask) { +tasks.register('migrateDevelopmentDatabase', FlywayMigrateTask) { url = devProps.getProperty("DB_URL") user = devProps.getProperty("DB_USER") password = devProps.getProperty("DB_PASSWORD") @@ -113,7 +121,7 @@ def testProps = new Properties() file("$rootProject.projectDir/src/test/resources/telraam/testConfig.properties").withInputStream { testProps.load(it) } -task migrateTestingDatabase(type: FlywayMigrateTask) { +tasks.register('migrateTestingDatabase', FlywayMigrateTask) { url = testProps.getProperty("DB_URL") baselineOnMigrate = true } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c023ec8b20f512888fe07c5bd3ff77bb8f..d64cd4917707c1f8861d8cb53dd15194d4248596 100644 GIT binary patch literal 43462 zcma&NWl&^owk(X(xVyW%ySuwf;qI=D6|RlDJ2cR^yEKh!@I- zp9QeisK*rlxC>+~7Dk4IxIRsKBHqdR9b3+fyL=ynHmIDe&|>O*VlvO+%z5;9Z$|DJ zb4dO}-R=MKr^6EKJiOrJdLnCJn>np?~vU-1sSFgPu;pthGwf}bG z(1db%xwr#x)r+`4AGu$j7~u2MpVs3VpLp|mx&;>`0p0vH6kF+D2CY0fVdQOZ@h;A` z{infNyvmFUiu*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GSRyU{Fnm`aqrr7bz42c5xsOO-~oZpkzorD1g}Y<6rk&3>PsSGy}W?MtqFky@A(X# zIuNZK0cK?^=;PUAu>j0#HtjbHCV*6?jzA&OoE$*Jlga*}LF`SF?WLhv1O|zqC<>*> zYB;#lsYKx0&kH@BFpW8n*yDcc6?;_zaJs<-jPSkCsSX-!aV=P5kUgF@Nu<{a%#K*F z134Q{9|YX7X(v$62_cY3^G%t~rD>Q0z@)1|zs)vjJ6Jq9;7#Ki`w+eS**En?7;n&7 zu==V3T&eFboN3ZiMx3D8qYc;VjFUk_H-WWCau(VFXSQf~viH0L$gwD$UfFHqNcgN`x}M+YQ6RnN<+@t>JUp#)9YOkqst-Ga?{FsDpEeX0(5v{0J~SEbWiL zXC2}M4?UH@u&|;%0y`eb33ldo4~z-x8zY!oVmV=c+f$m?RfDC35mdQ2E>Pze7KWP- z>!Bh<&57I+O_^s}9Tg^k)h7{xx@0a0IA~GAOt2yy!X%Q$1rt~LbTB6@Du!_0%HV>N zlf)QI1&gvERKwso23mJ!Ou6ZS#zCS5W`gxE5T>C#E|{i<1D35C222I33?Njaz`On7 zi<+VWFP6D{e-{yiN#M|Jgk<44u1TiMI78S5W`Sdb5f+{zu34s{CfWN7a3Cf^@L%!& zN$?|!!9j2c)j$~+R6n#891w-z8(!oBpL2K=+%a$r2|~8-(vQj5_XT`<0Ksf;oP+tz z9CObS!0m)Tgg`K#xBM8B(|Z)Wb&DYL{WTYv`;A=q6~Nnx2+!lTIXtj8J7dZE!P_{z z#f8w6F}^!?^KE#+ZDv+xd5O&3EmomZzsv?>E-~ygGum45fk!SBN&|eo1rKw^?aZJ4 E2O(~oYXATM diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ffed3a2..a80b22c 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,99 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index ac1b06f..7101f8e 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +41,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/settings.gradle b/settings.gradle index fee0901..0c809d4 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1 @@ rootProject.name = 'telraam' - diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 12d7851..8729ea2 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -1,13 +1,15 @@ package telraam; -import io.dropwizard.Application; +import io.dropwizard.core.Application; import io.dropwizard.jdbi3.JdbiFactory; import io.dropwizard.jdbi3.bundles.JdbiExceptionsBundle; import io.dropwizard.jersey.setup.JerseyEnvironment; -import io.dropwizard.setup.Bootstrap; -import io.dropwizard.setup.Environment; +import io.dropwizard.core.setup.Bootstrap; +import io.dropwizard.core.setup.Environment; import io.federecio.dropwizard.swagger.SwaggerBundle; import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.FilterRegistration; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.jdbi.v3.core.Jdbi; import telraam.api.*; @@ -20,8 +22,6 @@ import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; -import javax.servlet.DispatcherType; -import javax.servlet.FilterRegistration; import java.io.IOException; import java.util.EnumSet; import java.util.HashSet; diff --git a/src/main/java/telraam/AppConfiguration.java b/src/main/java/telraam/AppConfiguration.java index 3a45777..15eefbc 100644 --- a/src/main/java/telraam/AppConfiguration.java +++ b/src/main/java/telraam/AppConfiguration.java @@ -1,14 +1,13 @@ package telraam; import com.fasterxml.jackson.annotation.JsonProperty; -import io.dropwizard.Configuration; +import io.dropwizard.core.Configuration; import io.dropwizard.db.DataSourceFactory; import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import telraam.api.responses.Template; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - public class AppConfiguration extends Configuration { @NotNull private String template; diff --git a/src/main/java/telraam/api/AbstractResource.java b/src/main/java/telraam/api/AbstractResource.java index ce0e097..bcd70d0 100644 --- a/src/main/java/telraam/api/AbstractResource.java +++ b/src/main/java/telraam/api/AbstractResource.java @@ -1,12 +1,13 @@ package telraam.api; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.Response; import telraam.database.daos.DAO; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; import java.util.Optional; public abstract class AbstractResource implements Resource { @@ -19,16 +20,14 @@ protected AbstractResource(DAO dao) { @Override // TODO Validate model and return 405 for wrong input - public int create(@ApiParam(required = true) T t) { + public int create(@Parameter(required = true) T t) { return dao.insert(t); } @Override - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid or no ID supplied"), // TODO validate ID, return 400 on wrong ID format - @ApiResponse(code = 404, message = "Entity with specified ID not found") - }) - public T get(@ApiParam(value = "ID of entity that needs to be fetched", required = true) Optional id) { + @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied") // TODO validate ID, return 400 on wrong ID format + @ApiResponse(responseCode = "404", description = "Entity with specified ID not found") + public T get(@Parameter(description = "ID of entity that needs to be fetched", required = true) Optional id) { if (id.isPresent()) { Optional optional = dao.getById(id.get()); if (optional.isPresent()) { @@ -42,12 +41,11 @@ public T get(@ApiParam(value = "ID of entity that needs to be fetched", required } @Override - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid or no ID supplied"), // TODO validate ID, return 400 on wrong ID format - @ApiResponse(code = 404, message = "Entity with specified ID not found"), - @ApiResponse(code = 405, message = "Validation exception")}) // TODO validate input, 405 on wrong input - public T update(@ApiParam(value = "Entity object that needs to be updated in the database", required = true) T t, - @ApiParam(value = "ID of entity that needs to be fetched", required = true) Optional id) { + @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied") // TODO validate ID, return 400 on wrong ID format + @ApiResponse(responseCode = "404", description = "Entity with specified ID not found") + @ApiResponse(responseCode = "405", description = "Validation exception") // TODO validate input, 405 on wrong input + public T update(@Parameter(description = "Entity object that needs to be updated in the database", required = true) T t, + @Parameter(description = "ID of entity that needs to be fetched", required = true) Optional id) { if (id.isPresent()) { Optional optionalBaton = dao.getById(id.get()); if (optionalBaton.isPresent()) { @@ -63,10 +61,10 @@ public T update(@ApiParam(value = "Entity object that needs to be updated in the @Override @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid or no ID supplied"), // TODO validate ID, return 400 on wrong ID format + @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied"), // TODO validate ID, return 400 on wrong ID format }) public boolean delete( - @ApiParam(value = "ID of entity that needs to be deleted", required = true) Optional id) { + @Parameter(description = "ID of entity that needs to be deleted", required = true) Optional id) { if (id.isPresent()) { return dao.deleteById(id.get()) == 1; } else { diff --git a/src/main/java/telraam/api/AcceptedLapsResource.java b/src/main/java/telraam/api/AcceptedLapsResource.java index 135c984..b413511 100644 --- a/src/main/java/telraam/api/AcceptedLapsResource.java +++ b/src/main/java/telraam/api/AcceptedLapsResource.java @@ -1,22 +1,22 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import telraam.database.models.Lap; import telraam.util.AcceptedLapsUtil; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; @Path("/accepted-laps") -@Api("/accepted-laps") +@Tag(name="Accpted Laps") @Produces(MediaType.APPLICATION_JSON) public class AcceptedLapsResource { @GET - @ApiOperation("Get all accepted laps") + @Operation(summary = "Get all accepted laps") public List getLaps() { return AcceptedLapsUtil.getInstance().getAcceptedLaps(); } diff --git a/src/main/java/telraam/api/BatonResource.java b/src/main/java/telraam/api/BatonResource.java index ccf8e46..49bcd68 100644 --- a/src/main/java/telraam/api/BatonResource.java +++ b/src/main/java/telraam/api/BatonResource.java @@ -1,18 +1,18 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.BatonDAO; import telraam.database.models.Baton; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/baton") // dropwizard -@Api(value = "/baton") // Swagger +@Tag(name = "Baton") @Produces(MediaType.APPLICATION_JSON) public class BatonResource extends AbstractListableResource { public BatonResource(BatonDAO dao) { @@ -20,31 +20,31 @@ public BatonResource(BatonDAO dao) { } @Override - @ApiOperation(value = "Find all batons") + @Operation(summary = "Find all batons") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Add a new baton to the database") + @Operation(summary = "Add a new baton to the database") public int create(Baton baton) { return super.create(baton); } @Override - @ApiOperation(value = "Find baton by ID") + @Operation(summary = "Find baton by ID") public Baton get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing baton") + @Operation(summary = "Update an existing baton") public Baton update(Baton baton, Optional id) { return super.update(baton, id); } @Override - @ApiOperation(value = "Delete an existing baton") + @Operation(summary = "Delete an existing baton") public boolean delete(Optional id) { return super.delete(id); } diff --git a/src/main/java/telraam/api/BatonSwitchoverResource.java b/src/main/java/telraam/api/BatonSwitchoverResource.java index f9f27f4..72a0b85 100644 --- a/src/main/java/telraam/api/BatonSwitchoverResource.java +++ b/src/main/java/telraam/api/BatonSwitchoverResource.java @@ -1,18 +1,18 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.models.BatonSwitchover; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/batonswitchover") // dropwizard -@Api(value = "/batonswitchover") // Swagger +@Tag(name="Baton Switchover") @Produces(MediaType.APPLICATION_JSON) public class BatonSwitchoverResource extends AbstractListableResource { public BatonSwitchoverResource(BatonSwitchoverDAO dao) { @@ -20,19 +20,19 @@ public BatonSwitchoverResource(BatonSwitchoverDAO dao) { } @Override - @ApiOperation(value = "Find all baton switchovers") + @Operation(summary = "Find all baton switchovers") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Find baton switchover by ID") + @Operation(summary = "Find baton switchover by ID") public BatonSwitchover get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Add a new baton switchover to the database") + @Operation(summary = "Add a new baton switchover to the database") public int create(BatonSwitchover batonSwitchover) { return super.create(batonSwitchover); } diff --git a/src/main/java/telraam/api/DetectionResource.java b/src/main/java/telraam/api/DetectionResource.java index 6ab0f35..c41a514 100644 --- a/src/main/java/telraam/api/DetectionResource.java +++ b/src/main/java/telraam/api/DetectionResource.java @@ -1,18 +1,18 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.DetectionDAO; import telraam.database.models.Detection; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/detection") -@Api(value = "/detection") // Swagger @Produces(MediaType.APPLICATION_JSON) +@Tag(name="Detection") public class DetectionResource extends AbstractListableResource { private final DetectionDAO detectionDAO; @@ -23,38 +23,38 @@ public DetectionResource(DetectionDAO dao) { } @Override - @ApiOperation(value = "Find all detections") + @Operation(summary = "Find all detections") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Add a new detection to the database") + @Operation(summary = "Add a new detection to the database") public int create(Detection detection) { return super.create(detection); } @Override - @ApiOperation(value = "Find detection by ID") + @Operation(summary = "Find detection by ID") public Detection get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing detection") + @Operation(summary = "Update an existing detection") public Detection update(Detection detection, Optional id) { return super.update(detection, id); } @Override - @ApiOperation(value = "Delete an existing detection") + @Operation(summary = "Delete an existing detection") public boolean delete(Optional id) { return super.delete(id); } @GET @Path("/since/{id}") - @ApiOperation(value = "Get detections with ID larger than given ID") + @Operation(summary = "Get detections with ID larger than given ID") public List getListSince(@PathParam("id") Integer id, @QueryParam("limit") Optional limit) { return detectionDAO.getSinceId(id, limit.orElse(1000)); } diff --git a/src/main/java/telraam/api/LapCountResource.java b/src/main/java/telraam/api/LapCountResource.java index b82be82..b8ca04d 100644 --- a/src/main/java/telraam/api/LapCountResource.java +++ b/src/main/java/telraam/api/LapCountResource.java @@ -1,22 +1,20 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.TeamDAO; import telraam.database.models.Lap; import telraam.database.models.Team; import telraam.util.AcceptedLapsUtil; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.Map; import java.util.Optional; @Path("/lap-counts") -@Api("/lap-counts") +@Tag(name="Lap Counts") @Produces(MediaType.APPLICATION_JSON) public class LapCountResource { TeamDAO teamDAO; @@ -26,7 +24,7 @@ public LapCountResource(TeamDAO teamDAO) { } @GET - @ApiOperation("Get the current lap counts per team") + @Operation(summary = "Get the current lap counts per team") public Map getLapCounts() { Map perId = new HashMap<>(); for (Lap lap : AcceptedLapsUtil.getInstance().getAcceptedLaps()) { diff --git a/src/main/java/telraam/api/LapResource.java b/src/main/java/telraam/api/LapResource.java index 29186e9..25da4b9 100644 --- a/src/main/java/telraam/api/LapResource.java +++ b/src/main/java/telraam/api/LapResource.java @@ -1,20 +1,17 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.LapDAO; import telraam.database.models.Lap; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/lap") -@Api("/lap") +@Tag(name="Lap") @Produces(MediaType.APPLICATION_JSON) public class LapResource extends AbstractResource { private final LapDAO lapDAO; @@ -25,7 +22,7 @@ public LapResource(LapDAO dao) { } @GET - @ApiOperation(value = "Find all laps") + @Operation(summary = "Find all laps") public List getListOf(@QueryParam("source") final Integer source) { if (source == null) { return lapDAO.getAll(); @@ -35,25 +32,25 @@ public List getListOf(@QueryParam("source") final Integer source) { } @Override - @ApiOperation(value = "Add a new lap to the database") + @Operation(summary = "Add a new lap to the database") public int create(Lap lap) { return super.create(lap); } @Override - @ApiOperation(value = "Find lap by ID") + @Operation(summary = "Find lap by ID") public Lap get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing lap") + @Operation(summary = "Update an existing lap") public Lap update(Lap lap, Optional id) { return super.update(lap, id); } @Override - @ApiOperation(value = "Delete an existing lap") + @Operation(summary = "Delete an existing lap") public boolean delete(Optional id) { return super.delete(id); } diff --git a/src/main/java/telraam/api/LapSourceResource.java b/src/main/java/telraam/api/LapSourceResource.java index e2037e3..bed07ac 100644 --- a/src/main/java/telraam/api/LapSourceResource.java +++ b/src/main/java/telraam/api/LapSourceResource.java @@ -1,18 +1,17 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.DAO; import telraam.database.models.LapSource; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/lap-source") -@Api("/lap-source") +@Tag(name = "Lap Source") @Produces(MediaType.APPLICATION_JSON) public class LapSourceResource extends AbstractListableResource { public LapSourceResource(DAO dao) { @@ -20,31 +19,31 @@ public LapSourceResource(DAO dao) { } @Override - @ApiOperation(value = "Find all lap sources") + @Operation(summary = "Find all lap sources") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Add a new lap source to the database") + @Operation(summary = "Add a new lap source to the database") public int create(LapSource lapSource) { return super.create(lapSource); } @Override - @ApiOperation(value = "Find lap source by ID") + @Operation(summary = "Find lap source by ID") public LapSource get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing lap source") + @Operation(summary = "Update an existing lap source") public LapSource update(LapSource lapSource, Optional id) { return super.update(lapSource, id); } @Override - @ApiOperation(value = "Delete an existing lap source") + @Operation(summary = "Delete an existing lap source") public boolean delete(Optional id) { return super.delete(id); } diff --git a/src/main/java/telraam/api/LapSourceSwitchoverResource.java b/src/main/java/telraam/api/LapSourceSwitchoverResource.java index cf07ef3..9ad4d1f 100644 --- a/src/main/java/telraam/api/LapSourceSwitchoverResource.java +++ b/src/main/java/telraam/api/LapSourceSwitchoverResource.java @@ -1,18 +1,17 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.LapSourceSwitchoverDAO; import telraam.database.models.LapSourceSwitchover; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/lapsourceswitchover") // dropwizard -@Api(value = "/lapsourceswitchover") // Swagger +@Tag(name="Lap Source Switchover") @Produces(MediaType.APPLICATION_JSON) public class LapSourceSwitchoverResource extends AbstractListableResource { public LapSourceSwitchoverResource(LapSourceSwitchoverDAO dao) { @@ -20,19 +19,19 @@ public LapSourceSwitchoverResource(LapSourceSwitchoverDAO dao) { } @Override - @ApiOperation(value = "Find all lap source switchovers") + @Operation(summary = "Find all lap source switchovers") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Find lap source switchover by ID") + @Operation(summary = "Find lap source switchover by ID") public LapSourceSwitchover get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Add a new lap source switchover to the database") + @Operation(summary = "Add a new lap source switchover to the database") public int create(LapSourceSwitchover lapSourceSwitchover) { return super.create(lapSourceSwitchover); } diff --git a/src/main/java/telraam/api/ListableResource.java b/src/main/java/telraam/api/ListableResource.java index e8bc2d5..24d84ea 100644 --- a/src/main/java/telraam/api/ListableResource.java +++ b/src/main/java/telraam/api/ListableResource.java @@ -1,6 +1,6 @@ package telraam.api; -import javax.ws.rs.GET; +import jakarta.ws.rs.GET; import java.util.List; /** diff --git a/src/main/java/telraam/api/MonitoringResource.java b/src/main/java/telraam/api/MonitoringResource.java index 01bbd9b..732b01a 100644 --- a/src/main/java/telraam/api/MonitoringResource.java +++ b/src/main/java/telraam/api/MonitoringResource.java @@ -1,7 +1,7 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import org.jdbi.v3.core.Jdbi; import telraam.database.daos.*; import telraam.database.models.Lap; @@ -16,12 +16,13 @@ import telraam.monitoring.models.LapCountForTeam; import telraam.monitoring.models.TeamLapInfo; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; + import java.util.*; @Path("/monitoring") -@Api("/monitoring") +@Tag(name = "Monitoring") @Produces(MediaType.APPLICATION_JSON) public class MonitoringResource { private final BatonStatusHolder batonStatusHolder; @@ -42,7 +43,7 @@ public MonitoringResource(Jdbi jdbi) { @GET @Path("/batons") - @ApiOperation(value = "Get the status of all the batons, including unused batons which are toggleable via a parameter") + @Operation(summary = "Get the status of all the batons, including unused batons which are toggleable via a parameter") public List getBatonMetrics(@QueryParam("filter_assigned") boolean filterAssigned) { List batonStatuses = batonStatusHolder.GetAllBatonStatuses(); if (filterAssigned) { @@ -58,28 +59,28 @@ public List getBatonMetrics(@QueryParam("filter_assigned") boolean @POST @Path("/reset-rebooted/{batonId}") - @ApiOperation(value = "Reset the rebooted flag of a baton") + @Operation(summary = "Reset the rebooted flag of a baton") public void resetRebooted(@PathParam("batonId") Integer batonId) { batonStatusHolder.resetRebooted(batonId); } @GET @Path("/team-detection-times") - @ApiOperation(value = "A map of all detections per batons") + @Operation(summary = "A map of all detections per batons") public Map> getTeamDetectionTimes() { return batonDetectionManager.getBatonDetections(); } @GET @Path("/stations-latest-detection-time") - @ApiOperation(value = "Get the map of all station name to time since last detection") + @Operation(summary = "Get the map of all station name to time since last detection") public Map getStationIDToLatestDetectionTimeMap() { return stationDetectionManager.timeSinceLastDetectionPerStation(); } @GET @Path("/team-lap-times/{lapperId}") - @ApiOperation(value = "Get monitoring data that can be used as grafana datasource") + @Operation(summary = "Get monitoring data that can be used as grafana datasource") public Map> getTeamLapTimes(@PathParam("lapperId") Integer id) { List laps = lapDAO.getAllBySourceSorted(id); List teams = teamDAO.getAll(); @@ -107,7 +108,7 @@ public Map> getTeamLapTimes(@PathParam("lapperId") In @GET @Path("/team-lap-counts") - @ApiOperation(value = "Get monitoring data that can be used as grafana datasource") + @Operation(summary = "Get monitoring data that can be used as grafana datasource") public List getTeamLapCounts() { List teams = teamDAO.getAll(); List lapSources = lapSourceDAO.getAll(); diff --git a/src/main/java/telraam/api/Resource.java b/src/main/java/telraam/api/Resource.java index 6228da0..5546cba 100644 --- a/src/main/java/telraam/api/Resource.java +++ b/src/main/java/telraam/api/Resource.java @@ -1,7 +1,8 @@ package telraam.api; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; + import java.util.Optional; public interface Resource { diff --git a/src/main/java/telraam/api/StationResource.java b/src/main/java/telraam/api/StationResource.java index 58c11ed..df61deb 100644 --- a/src/main/java/telraam/api/StationResource.java +++ b/src/main/java/telraam/api/StationResource.java @@ -1,18 +1,18 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Produces; import telraam.database.daos.DAO; import telraam.database.models.Station; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Path("/station") -@Api(value = "/station") // Swagger +@Tag(name="Station") @Produces(MediaType.APPLICATION_JSON) public class StationResource extends AbstractListableResource { public StationResource(DAO dao) { @@ -20,31 +20,31 @@ public StationResource(DAO dao) { } @Override - @ApiOperation(value = "Find all stations") + @Operation(summary = "Find all stations") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Add a new station to the database") + @Operation(summary = "Add a new station to the database") public int create(Station station) { return super.create(station); } @Override - @ApiOperation(value = "Find station by ID") + @Operation(summary = "Find station by ID") public Station get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing station") + @Operation(summary = "Update an existing station") public Station update(Station station, Optional id) { return super.update(station, id); } @Override - @ApiOperation(value = "Delete an existing station") + @Operation(summary = "Delete an existing station") public boolean delete(Optional id) { return super.delete(id); } diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 6a1ac54..64201dd 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -1,15 +1,15 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Produces; import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.daos.TeamDAO; import telraam.database.models.BatonSwitchover; import telraam.database.models.Team; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.MediaType; import java.sql.Timestamp; import java.time.Instant; import java.util.List; @@ -18,7 +18,7 @@ @Path("/team") -@Api("/team") +@Tag(name="Team") @Produces(MediaType.APPLICATION_JSON) public class TeamResource extends AbstractListableResource { BatonSwitchoverDAO batonSwitchoverDAO; @@ -29,13 +29,13 @@ public TeamResource(TeamDAO teamDAO, BatonSwitchoverDAO batonSwitchoverDAO) { } @Override - @ApiOperation(value = "Find all teams") + @Operation(summary = "Find all teams") public List getListOf() { return super.getListOf(); } @Override - @ApiOperation(value = "Add a new team to the database") + @Operation(summary = "Add a new team to the database") public int create(Team team) { int ret = super.create(team); @@ -52,13 +52,13 @@ public int create(Team team) { } @Override - @ApiOperation(value = "Find team by ID") + @Operation(summary = "Find team by ID") public Team get(Optional id) { return super.get(id); } @Override - @ApiOperation(value = "Update an existing team") + @Operation(summary = "Update an existing team") public Team update(Team team, Optional id) { Team previousTeam = this.get(id); Team ret = super.update(team, id); @@ -79,7 +79,7 @@ public Team update(Team team, Optional id) { } @Override - @ApiOperation(value = "Delete an existing team") + @Operation(summary = "Delete an existing team") public boolean delete(Optional id) { return super.delete(id); } diff --git a/src/main/java/telraam/api/TimeResource.java b/src/main/java/telraam/api/TimeResource.java index 1abc075..ebdae5f 100644 --- a/src/main/java/telraam/api/TimeResource.java +++ b/src/main/java/telraam/api/TimeResource.java @@ -1,15 +1,14 @@ package telraam.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; @Path("/time") -@Api("/time") +@Tag(name = "Time") @Produces(MediaType.APPLICATION_JSON) public class TimeResource { static class TimeResponse { @@ -21,7 +20,7 @@ public TimeResponse() { } @GET - @ApiOperation(value = "Get current time") + @Operation(summary = "Get current time") public TimeResponse get() { return new TimeResponse(); } diff --git a/src/main/java/telraam/logic/external/ExternalLapperResource.java b/src/main/java/telraam/logic/external/ExternalLapperResource.java index d640f6b..37f8e58 100644 --- a/src/main/java/telraam/logic/external/ExternalLapperResource.java +++ b/src/main/java/telraam/logic/external/ExternalLapperResource.java @@ -1,20 +1,15 @@ package telraam.logic.external; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; import telraam.logic.external.models.ExternalLapperStats; import telraam.logic.external.models.ExternalLapperTeamLaps; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import java.util.List; @Path("/lappers/external") -@Api("/lappers/external") @Produces(MediaType.APPLICATION_JSON) public class ExternalLapperResource { private final ExternalLapper lapper; @@ -28,21 +23,21 @@ public ExternalLapperResource(ExternalLapper lapper) { @POST @Path("/laps") - @ApiOperation(value = "Post the current laps") + @Operation(summary = "Post the current laps") public void postLaps(List teamLaps) { this.lapper.saveLaps(teamLaps); } @GET @Path("/stats") - @ApiOperation(value = "Get lapper statistics") + @Operation(summary = "Get lapper statistics") public ExternalLapperStats getStats() { return externalLapperStats; } @POST @Path("/stats") - @ApiOperation(value = "Post lapper statistics") + @Operation(summary = "Post lapper statistics") public void postStats(ExternalLapperStats externalLapperStats) { this.externalLapperStats = externalLapperStats; } diff --git a/src/test/java/telraam/DatabaseTest.java b/src/test/java/telraam/DatabaseTest.java index f490379..ac1f4f8 100644 --- a/src/test/java/telraam/DatabaseTest.java +++ b/src/test/java/telraam/DatabaseTest.java @@ -1,8 +1,8 @@ package telraam; +import io.dropwizard.core.setup.Environment; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.db.ManagedDataSource; -import io.dropwizard.setup.Environment; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; @@ -34,6 +34,7 @@ public static void initialize() { flyway = Flyway.configure() .dataSource(ds) .schemas() + .cleanDisabled(false) .load(); jdbi = ((App) APP_EXTENSION.getApplication()).getDatabase(); } diff --git a/src/test/java/telraam/api/BatonResourceTest.java b/src/test/java/telraam/api/BatonResourceTest.java index 8aca073..95a085c 100644 --- a/src/test/java/telraam/api/BatonResourceTest.java +++ b/src/test/java/telraam/api/BatonResourceTest.java @@ -1,5 +1,6 @@ package telraam.api; +import jakarta.ws.rs.WebApplicationException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import telraam.DatabaseTest; @@ -9,7 +10,6 @@ import java.util.HashSet; import java.util.Optional; import java.util.Set; -import javax.ws.rs.WebApplicationException; import static org.junit.jupiter.api.Assertions.*; From dc79ea14ccfd9680e94c348921baed660a7a6c80 Mon Sep 17 00:00:00 2001 From: Jonas Meeuws Date: Thu, 28 Mar 2024 16:56:38 +0100 Subject: [PATCH 30/90] Added websocket endpoint and singleton for sending messages from any class. --- build.gradle | 3 ++ src/main/java/telraam/App.java | 12 +++++- .../websocket/WebSocketConnection.java | 41 +++++++++++++++++++ .../websocket/WebSocketMessageSingleton.java | 37 +++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/main/java/telraam/websocket/WebSocketConnection.java create mode 100644 src/main/java/telraam/websocket/WebSocketMessageSingleton.java diff --git a/build.gradle b/build.gradle index 1d4df44..6800130 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,7 @@ sourceCompatibility = 17 // Set our project variables project.ext { dropwizardVersion = '4.0.5' + jettyVersion = '11.0.19' } repositories { @@ -62,6 +63,8 @@ dependencies { 'io.dropwizard:dropwizard-hibernate:' + dropwizardVersion, 'io.dropwizard:dropwizard-auth:' + dropwizardVersion, 'io.dropwizard:dropwizard-jdbi3:' + dropwizardVersion, + 'org.eclipse.jetty.websocket:websocket-jetty-api:' + jettyVersion, + 'org.eclipse.jetty.websocket:websocket-jetty-server:' + jettyVersion, ) // Database implementation('com.h2database:h2:2.2.220') diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 8729ea2..d7bfdba 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -11,6 +11,7 @@ import jakarta.servlet.DispatcherType; import jakarta.servlet.FilterRegistration; import org.eclipse.jetty.servlets.CrossOriginFilter; +import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.jdbi.v3.core.Jdbi; import telraam.api.*; import telraam.database.daos.*; @@ -21,6 +22,7 @@ import telraam.logic.robust.RobustLapper; import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; +import telraam.websocket.WebSocketConnection; import java.io.IOException; import java.util.EnumSet; @@ -78,6 +80,15 @@ public void run(AppConfiguration configuration, Environment environment) throws // Initialize AcceptedLapUtil AcceptedLapsUtil.createInstance(this.database); + // Register websocket endpoint + JettyWebSocketServletContainerInitializer.configure( + environment.getApplicationContext(), + (servletContext, wsContainer) -> { + wsContainer.setMaxTextMessageSize(65535); + wsContainer.addMapping("/ws", (req, res) -> new WebSocketConnection()); + } + ); + // Add api resources JerseyEnvironment jersey = environment.jersey(); jersey.register(new BatonResource(database.onDemand(BatonDAO.class))); @@ -94,7 +105,6 @@ public void run(AppConfiguration configuration, Environment environment) throws jersey.register(new MonitoringResource(database)); environment.healthChecks().register("template", new TemplateHealthCheck(configuration.getTemplate())); - // Enable CORS final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); diff --git a/src/main/java/telraam/websocket/WebSocketConnection.java b/src/main/java/telraam/websocket/WebSocketConnection.java new file mode 100644 index 0000000..191fea0 --- /dev/null +++ b/src/main/java/telraam/websocket/WebSocketConnection.java @@ -0,0 +1,41 @@ +package telraam.websocket; + +import java.io.IOException; +import java.util.logging.Logger; + +import org.eclipse.jetty.websocket.api.Session; +import org.eclipse.jetty.websocket.api.WebSocketAdapter; + +public class WebSocketConnection extends WebSocketAdapter { + private static final Logger logger = Logger.getLogger(WebSocketConnection.class.getName()); + + @Override + public void onWebSocketConnect(Session session) { + super.onWebSocketConnect(session); + WebSocketMessageSingleton.getInstance().registerConnection(this); + logger.info("Instance with remote \"%s\" connected".formatted(getRemote().getRemoteAddress())); + } + + @Override + public void onWebSocketClose(int statusCode, String reason) { + super.onWebSocketClose(statusCode, reason); + WebSocketMessageSingleton.getInstance().unregisterConnection(this); + logger.info("Instance with remote \"%s\" closed: [%s] %s".formatted(getRemote().getRemoteAddress(), statusCode, reason)); + } + + @Override + public void onWebSocketError(Throwable cause) { + super.onWebSocketError(cause); + logger.severe("WebSocket error in instance with remote \"%s\": %s".formatted(getRemote().getRemoteAddress(), cause)); + } + + public void send(String s) { + try { + getRemote().sendString(s); + } catch (IOException e) { + logger.severe("Sending \"%s\" through instance with remote \"%s\" failed with %s".formatted(s, getRemote().getRemoteAddress(), e)); + return; + } + logger.finest("Sent \"%s\" through instance with remote \"%s\"".formatted(s, getRemote().getRemoteAddress())); + } +} diff --git a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java new file mode 100644 index 0000000..9749d6d --- /dev/null +++ b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java @@ -0,0 +1,37 @@ +package telraam.websocket; + +import lombok.Getter; + +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; + +public class WebSocketMessageSingleton { + private static final Logger logger = Logger.getLogger(WebSocketMessageSingleton.class.getName()); + + @Getter + private static final WebSocketMessageSingleton instance = new WebSocketMessageSingleton(); + private static final Set registeredConnections = new HashSet<>(); + + private WebSocketMessageSingleton() { + } + + public void registerConnection(WebSocketConnection conn) { + boolean modified = registeredConnections.add(conn); + if (modified) { + logger.info("Registered WebSocketConnection %s".formatted(conn)); + } + } + + public void unregisterConnection(WebSocketConnection conn) { + boolean modified = registeredConnections.remove(conn); + if (modified) { + logger.info("Unregistered WebSocketConnection %s".formatted(conn)); + } + } + + public void sendToAll(String s) { + logger.info("Sending \"%s\" to all registered WebSocketConnection instances".formatted(s)); + registeredConnections.forEach(conn -> conn.send(s)); + } +} From b5833b2f7ca20fe1c6ae0665526bd3766acf002f Mon Sep 17 00:00:00 2001 From: Jonas Meeuws Date: Thu, 28 Mar 2024 22:27:21 +0100 Subject: [PATCH 31/90] Add websocket send example in TeamResource::create() Should close #111 when merged --- src/main/java/telraam/api/TeamResource.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 64201dd..22c36a6 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -16,6 +16,8 @@ import java.util.Objects; import java.util.Optional; +import telraam.websocket.WebSocketMessageSingleton; + @Path("/team") @Tag(name="Team") @@ -48,6 +50,14 @@ public int create(Team team) { )); } + WebSocketMessageSingleton.getInstance().sendToAll( + "new team (%s, %s, %s)".formatted( + team.getName(), + team.getId(), + team.getBatonId() + ) + ); + return ret; } From a1f9ee1ff8ba6019316da01c5258dc1f05dea4ba Mon Sep 17 00:00:00 2001 From: Jonas Meeuws Date: Thu, 28 Mar 2024 23:06:10 +0100 Subject: [PATCH 32/90] change sendToAll log level: info -> finest --- src/main/java/telraam/websocket/WebSocketMessageSingleton.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java index 9749d6d..de12115 100644 --- a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java +++ b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java @@ -31,7 +31,7 @@ public void unregisterConnection(WebSocketConnection conn) { } public void sendToAll(String s) { - logger.info("Sending \"%s\" to all registered WebSocketConnection instances".formatted(s)); + logger.finest("Sending \"%s\" to all registered WebSocketConnection instances".formatted(s)); registeredConnections.forEach(conn -> conn.send(s)); } } From afa2b62c0f6c2bcd6eee2ea83ee70be18e00ca81 Mon Sep 17 00:00:00 2001 From: Michiel Lachaert Date: Thu, 28 Mar 2024 23:39:40 +0100 Subject: [PATCH 33/90] add new migration to remove null constraint from newbationid --- .../db/migration/V15__remove_null_constraint_on_newbatonid.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/main/resources/db/migration/V15__remove_null_constraint_on_newbatonid.sql diff --git a/src/main/resources/db/migration/V15__remove_null_constraint_on_newbatonid.sql b/src/main/resources/db/migration/V15__remove_null_constraint_on_newbatonid.sql new file mode 100644 index 0000000..0f7ae17 --- /dev/null +++ b/src/main/resources/db/migration/V15__remove_null_constraint_on_newbatonid.sql @@ -0,0 +1 @@ +alter table batonswitchover alter column newbatonid drop not null; \ No newline at end of file From 5d42686d1b858a6371ca3f540e50472065028106 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 00:53:35 +0100 Subject: [PATCH 34/90] Removed websocket message --- src/main/java/telraam/api/TeamResource.java | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 22c36a6..56975c9 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -2,22 +2,20 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.daos.TeamDAO; import telraam.database.models.BatonSwitchover; import telraam.database.models.Team; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.core.MediaType; import java.sql.Timestamp; import java.time.Instant; import java.util.List; import java.util.Objects; import java.util.Optional; -import telraam.websocket.WebSocketMessageSingleton; - @Path("/team") @Tag(name="Team") @@ -50,14 +48,6 @@ public int create(Team team) { )); } - WebSocketMessageSingleton.getInstance().sendToAll( - "new team (%s, %s, %s)".formatted( - team.getName(), - team.getId(), - team.getBatonId() - ) - ); - return ret; } From 2938da5b9559c09b00eb56a5724fb1414cf8f668 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Fri, 29 Mar 2024 13:28:41 +0100 Subject: [PATCH 35/90] use lombok in external lapper --- .../logic/external/ExternalLapper.java | 4 +-- .../external/models/ExternalLapperLap.java | 6 +++- .../external/models/ExternalLapperStats.java | 28 +++---------------- .../models/ExternalLapperTeamLaps.java | 9 ++++-- 4 files changed, 18 insertions(+), 29 deletions(-) diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/external/ExternalLapper.java index d2e7e34..3aee9f2 100644 --- a/src/main/java/telraam/logic/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/external/ExternalLapper.java @@ -46,8 +46,8 @@ public void saveLaps(List teamLaps) { // Find which laps are no longer needed or have to be added for (ExternalLapperTeamLaps teamLap : teamLaps) { - List lapsForTeam = laps.stream().filter(l -> l.getTeamId() == teamLap.teamId).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); - List newLapsForTeam = teamLap.laps.stream().map(nl -> new Lap(teamLap.teamId, lapSourceId, new Timestamp((long) (nl.timestamp)))).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); + List lapsForTeam = laps.stream().filter(l -> l.getTeamId() == teamLap.getTeamId()).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); + List newLapsForTeam = teamLap.getLaps().stream().map(nl -> new Lap(teamLap.getTeamId(), lapSourceId, new Timestamp((long) (nl.getTimestamp())))).sorted(Comparator.comparing(Lap::getTimestamp)).toList(); int lapsIndex = 0; int newLapsIndex = 0; diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperLap.java b/src/main/java/telraam/logic/external/models/ExternalLapperLap.java index 724ec5f..f343ce1 100644 --- a/src/main/java/telraam/logic/external/models/ExternalLapperLap.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperLap.java @@ -1,5 +1,9 @@ package telraam.logic.external.models; +import lombok.Getter; +import lombok.Setter; + +@Getter @Setter public class ExternalLapperLap { - public double timestamp; + private double timestamp; } diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperStats.java b/src/main/java/telraam/logic/external/models/ExternalLapperStats.java index 74598d3..cc31a04 100644 --- a/src/main/java/telraam/logic/external/models/ExternalLapperStats.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperStats.java @@ -1,33 +1,13 @@ package telraam.logic.external.models; +import lombok.Getter; +import lombok.Setter; + import java.util.List; +@Setter @Getter public class ExternalLapperStats { private List errorHistory; private List> transitionMatrix; private List> emissionMatrix; - - public List getErrorHistory() { - return errorHistory; - } - - public void setErrorHistory(List errorHistory) { - this.errorHistory = errorHistory; - } - - public List> getTransitionMatrix() { - return transitionMatrix; - } - - public void setTransitionMatrix(List> transitionMatrix) { - this.transitionMatrix = transitionMatrix; - } - - public List> getEmissionMatrix() { - return emissionMatrix; - } - - public void setEmissionMatrix(List> emissionMatrix) { - this.emissionMatrix = emissionMatrix; - } } diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java b/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java index c184222..c8e8170 100644 --- a/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java +++ b/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java @@ -1,8 +1,13 @@ package telraam.logic.external.models; +import lombok.Getter; +import lombok.Setter; + import java.util.List; + +@Getter @Setter public class ExternalLapperTeamLaps { - public int teamId; - public List laps; + private int teamId; + private List laps; } From ee0988c22e49222fcd5ae1ff9b4024eb4db5fcdb Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 26 Mar 2024 00:29:36 +0100 Subject: [PATCH 36/90] added simple positioner --- .../logic/positioners/CircularQueue.java | 30 +++++++++ .../logic/positioners/SimplePositioner.java | 66 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/main/java/telraam/logic/positioners/CircularQueue.java create mode 100644 src/main/java/telraam/logic/positioners/SimplePositioner.java diff --git a/src/main/java/telraam/logic/positioners/CircularQueue.java b/src/main/java/telraam/logic/positioners/CircularQueue.java new file mode 100644 index 0000000..eb0c403 --- /dev/null +++ b/src/main/java/telraam/logic/positioners/CircularQueue.java @@ -0,0 +1,30 @@ +package telraam.logic.positioners; + +import java.util.LinkedList; + +public class CircularQueue extends LinkedList { + + private final int maxSize; + private int size = 0; + + public CircularQueue(int maxSize) { + this.maxSize = maxSize; + } + + @Override + public boolean add(T e) { + if (this.size >= this.maxSize) { + super.removeFirst(); + this.size--; + } + + boolean result = super.add(e); + + if (result) { + this.size++; + } + + return result; + } + +} diff --git a/src/main/java/telraam/logic/positioners/SimplePositioner.java b/src/main/java/telraam/logic/positioners/SimplePositioner.java new file mode 100644 index 0000000..83d2872 --- /dev/null +++ b/src/main/java/telraam/logic/positioners/SimplePositioner.java @@ -0,0 +1,66 @@ +package telraam.logic.positioners; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.BatonSwitchover; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.database.models.Team; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SimplePositioner { + private final int QUEUE_SIZE = 50; + private final int MIN_RSSI = -85; + private Map teamIdToTeam = new HashMap<>(); + private Map> teamDetections = new HashMap<>(); + private List stations; + + public SimplePositioner(Jdbi jdbi) { + TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); + List teams = teamDAO.getAll(); + for (Team team: teams) { + this.teamDetections.put(team, new CircularQueue<>(QUEUE_SIZE)); + } + List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); + switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); + + for (BatonSwitchover switchover: switchovers) { + this.teamIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); + } + + List stationList = jdbi.onDemand(StationDAO.class).getAll(); + stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); + this.stations = stationList.stream().map(Station::getId).toList(); + } + + private void calculatePosition(Team team) { + List detections = this.teamDetections.get(team); + detections.sort(Comparator.comparing(Detection::getTimestamp)); + + int currentStationRssi = MIN_RSSI; + int currentStationPosition = 0; + for (Detection detection: detections) { + if (detection.getRssi() > currentStationRssi) { + currentStationRssi = detection.getRssi(); + currentStationPosition = detection.getStationId(); + } + } + + float progress = ((float) 100 / this.stations.size()) * this.stations.indexOf(currentStationPosition); + + System.out.printf("Team: %s | Progress: %f | Acceleration: %f%n", team.getName(), progress, 1.0); + } + + public void handle(Detection detection) { + Team team = this.teamIdToTeam.get(detection.getBatonId()); + this.teamDetections.get(team).add(detection); + this.calculatePosition(team); + } + +} From c4abdd9f1d65ff10f3247d640ab2a609bf2a0f0a Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 11:17:40 +0100 Subject: [PATCH 37/90] refactor --- src/main/java/telraam/logic/{ => lapper}/Lapper.java | 0 .../telraam/logic/{ => lapper}/external/ExternalLapper.java | 0 .../logic/{ => lapper}/external/ExternalLapperResource.java | 0 .../logic/{ => lapper}/external/models/ExternalLapperLap.java | 0 .../{ => lapper}/external/models/ExternalLapperStats.java | 0 .../{ => lapper}/external/models/ExternalLapperTeamLaps.java | 0 .../java/telraam/logic/{ => lapper}/robust/RobustLapper.java | 0 .../java/telraam/logic/{ => lapper}/simple/SimpleLapper.java | 0 .../logic/{positioners => positioner}/CircularQueue.java | 0 src/main/java/telraam/logic/positioner/Position.java | 4 ++++ .../logic/{positioners => positioner}/SimplePositioner.java | 0 11 files changed, 4 insertions(+) rename src/main/java/telraam/logic/{ => lapper}/Lapper.java (100%) rename src/main/java/telraam/logic/{ => lapper}/external/ExternalLapper.java (100%) rename src/main/java/telraam/logic/{ => lapper}/external/ExternalLapperResource.java (100%) rename src/main/java/telraam/logic/{ => lapper}/external/models/ExternalLapperLap.java (100%) rename src/main/java/telraam/logic/{ => lapper}/external/models/ExternalLapperStats.java (100%) rename src/main/java/telraam/logic/{ => lapper}/external/models/ExternalLapperTeamLaps.java (100%) rename src/main/java/telraam/logic/{ => lapper}/robust/RobustLapper.java (100%) rename src/main/java/telraam/logic/{ => lapper}/simple/SimpleLapper.java (100%) rename src/main/java/telraam/logic/{positioners => positioner}/CircularQueue.java (100%) create mode 100644 src/main/java/telraam/logic/positioner/Position.java rename src/main/java/telraam/logic/{positioners => positioner}/SimplePositioner.java (100%) diff --git a/src/main/java/telraam/logic/Lapper.java b/src/main/java/telraam/logic/lapper/Lapper.java similarity index 100% rename from src/main/java/telraam/logic/Lapper.java rename to src/main/java/telraam/logic/lapper/Lapper.java diff --git a/src/main/java/telraam/logic/external/ExternalLapper.java b/src/main/java/telraam/logic/lapper/external/ExternalLapper.java similarity index 100% rename from src/main/java/telraam/logic/external/ExternalLapper.java rename to src/main/java/telraam/logic/lapper/external/ExternalLapper.java diff --git a/src/main/java/telraam/logic/external/ExternalLapperResource.java b/src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java similarity index 100% rename from src/main/java/telraam/logic/external/ExternalLapperResource.java rename to src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperLap.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java similarity index 100% rename from src/main/java/telraam/logic/external/models/ExternalLapperLap.java rename to src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperStats.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java similarity index 100% rename from src/main/java/telraam/logic/external/models/ExternalLapperStats.java rename to src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java diff --git a/src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java similarity index 100% rename from src/main/java/telraam/logic/external/models/ExternalLapperTeamLaps.java rename to src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java diff --git a/src/main/java/telraam/logic/robust/RobustLapper.java b/src/main/java/telraam/logic/lapper/robust/RobustLapper.java similarity index 100% rename from src/main/java/telraam/logic/robust/RobustLapper.java rename to src/main/java/telraam/logic/lapper/robust/RobustLapper.java diff --git a/src/main/java/telraam/logic/simple/SimpleLapper.java b/src/main/java/telraam/logic/lapper/simple/SimpleLapper.java similarity index 100% rename from src/main/java/telraam/logic/simple/SimpleLapper.java rename to src/main/java/telraam/logic/lapper/simple/SimpleLapper.java diff --git a/src/main/java/telraam/logic/positioners/CircularQueue.java b/src/main/java/telraam/logic/positioner/CircularQueue.java similarity index 100% rename from src/main/java/telraam/logic/positioners/CircularQueue.java rename to src/main/java/telraam/logic/positioner/CircularQueue.java diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java new file mode 100644 index 0000000..988120c --- /dev/null +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -0,0 +1,4 @@ +package telraam.logic.positioner; + +public class Position { +} diff --git a/src/main/java/telraam/logic/positioners/SimplePositioner.java b/src/main/java/telraam/logic/positioner/SimplePositioner.java similarity index 100% rename from src/main/java/telraam/logic/positioners/SimplePositioner.java rename to src/main/java/telraam/logic/positioner/SimplePositioner.java From 2a9cd403a2a961904ace8e0c0c6b4c35b76cbbe5 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 11:17:57 +0100 Subject: [PATCH 38/90] refactor --- src/main/java/telraam/App.java | 6 ++--- .../java/telraam/logic/lapper/Lapper.java | 2 +- .../logic/lapper/external/ExternalLapper.java | 6 ++--- .../external/ExternalLapperResource.java | 6 ++--- .../external/models/ExternalLapperLap.java | 2 +- .../external/models/ExternalLapperStats.java | 2 +- .../models/ExternalLapperTeamLaps.java | 2 +- .../logic/lapper/robust/RobustLapper.java | 4 +-- .../logic/lapper/simple/SimpleLapper.java | 4 +-- .../logic/positioner/CircularQueue.java | 2 +- .../telraam/logic/positioner/Position.java | 27 ++++++++++++++++++- .../logic/positioner/SimplePositioner.java | 2 +- src/main/java/telraam/station/Fetcher.java | 2 +- .../logic/simple/SimpleLapperTest.java | 4 +-- 14 files changed, 48 insertions(+), 23 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index d7bfdba..5c93fe8 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -17,9 +17,9 @@ import telraam.database.daos.*; import telraam.database.models.Station; import telraam.healthchecks.TemplateHealthCheck; -import telraam.logic.Lapper; -import telraam.logic.external.ExternalLapper; -import telraam.logic.robust.RobustLapper; +import telraam.logic.lapper.Lapper; +import telraam.logic.lapper.external.ExternalLapper; +import telraam.logic.lapper.robust.RobustLapper; import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; import telraam.websocket.WebSocketConnection; diff --git a/src/main/java/telraam/logic/lapper/Lapper.java b/src/main/java/telraam/logic/lapper/Lapper.java index c3dc674..d999307 100644 --- a/src/main/java/telraam/logic/lapper/Lapper.java +++ b/src/main/java/telraam/logic/lapper/Lapper.java @@ -1,4 +1,4 @@ -package telraam.logic; +package telraam.logic.lapper; import io.dropwizard.jersey.setup.JerseyEnvironment; import telraam.database.models.Detection; diff --git a/src/main/java/telraam/logic/lapper/external/ExternalLapper.java b/src/main/java/telraam/logic/lapper/external/ExternalLapper.java index 3aee9f2..510e28a 100644 --- a/src/main/java/telraam/logic/lapper/external/ExternalLapper.java +++ b/src/main/java/telraam/logic/lapper/external/ExternalLapper.java @@ -1,4 +1,4 @@ -package telraam.logic.external; +package telraam.logic.lapper.external; import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; @@ -7,8 +7,8 @@ import telraam.database.models.Detection; import telraam.database.models.Lap; import telraam.database.models.LapSource; -import telraam.logic.Lapper; -import telraam.logic.external.models.ExternalLapperTeamLaps; +import telraam.logic.lapper.Lapper; +import telraam.logic.lapper.external.models.ExternalLapperTeamLaps; import java.sql.Timestamp; import java.util.Comparator; diff --git a/src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java b/src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java index 37f8e58..55f6aa0 100644 --- a/src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java +++ b/src/main/java/telraam/logic/lapper/external/ExternalLapperResource.java @@ -1,10 +1,10 @@ -package telraam.logic.external; +package telraam.logic.lapper.external; import io.swagger.v3.oas.annotations.Operation; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; -import telraam.logic.external.models.ExternalLapperStats; -import telraam.logic.external.models.ExternalLapperTeamLaps; +import telraam.logic.lapper.external.models.ExternalLapperStats; +import telraam.logic.lapper.external.models.ExternalLapperTeamLaps; import java.util.List; diff --git a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java index f343ce1..3623891 100644 --- a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java +++ b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperLap.java @@ -1,4 +1,4 @@ -package telraam.logic.external.models; +package telraam.logic.lapper.external.models; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java index cc31a04..8c875bc 100644 --- a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java +++ b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperStats.java @@ -1,4 +1,4 @@ -package telraam.logic.external.models; +package telraam.logic.lapper.external.models; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java index c8e8170..fa37f63 100644 --- a/src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java +++ b/src/main/java/telraam/logic/lapper/external/models/ExternalLapperTeamLaps.java @@ -1,4 +1,4 @@ -package telraam.logic.external.models; +package telraam.logic.lapper.external.models; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/telraam/logic/lapper/robust/RobustLapper.java b/src/main/java/telraam/logic/lapper/robust/RobustLapper.java index 2ad64c5..62ae807 100644 --- a/src/main/java/telraam/logic/lapper/robust/RobustLapper.java +++ b/src/main/java/telraam/logic/lapper/robust/RobustLapper.java @@ -1,4 +1,4 @@ -package telraam.logic.robust; +package telraam.logic.lapper.robust; import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; @@ -10,7 +10,7 @@ import telraam.database.models.Lap; import telraam.database.models.LapSource; import telraam.database.models.Station; -import telraam.logic.Lapper; +import telraam.logic.lapper.Lapper; import java.sql.Timestamp; import java.util.*; diff --git a/src/main/java/telraam/logic/lapper/simple/SimpleLapper.java b/src/main/java/telraam/logic/lapper/simple/SimpleLapper.java index 9b26f9b..608e724 100644 --- a/src/main/java/telraam/logic/lapper/simple/SimpleLapper.java +++ b/src/main/java/telraam/logic/lapper/simple/SimpleLapper.java @@ -1,11 +1,11 @@ -package telraam.logic.simple; +package telraam.logic.lapper.simple; import io.dropwizard.jersey.setup.JerseyEnvironment; import org.jdbi.v3.core.Jdbi; import telraam.database.daos.LapDAO; import telraam.database.daos.LapSourceDAO; import telraam.database.models.*; -import telraam.logic.Lapper; +import telraam.logic.lapper.Lapper; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/telraam/logic/positioner/CircularQueue.java b/src/main/java/telraam/logic/positioner/CircularQueue.java index eb0c403..042ba79 100644 --- a/src/main/java/telraam/logic/positioner/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/CircularQueue.java @@ -1,4 +1,4 @@ -package telraam.logic.positioners; +package telraam.logic.positioner; import java.util.LinkedList; diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 988120c..23bcf00 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -1,4 +1,29 @@ -package telraam.logic.positioner; +package telraam.logic.positioners; +import lombok.Getter; +import lombok.Setter; +import telraam.database.models.Team; +import telraam.websocket.WebSocketMessageSingleton; + +@Getter @Setter public class Position { + private Team team; + private float progress; // Progress of the lap. Between 0-1 + private float speed; // Current speed. Progress / second + + public Position(Team team) { + this.team = team; + this.progress = 0; + this.speed = 0; + } + + private String toWebsocketMessage() { + return String.format("{\"topic\": \"position\", \"data\": {\"team\": %d, \"progress\": %.4f, \"speed\": %.5f}}", team.getId(), this.progress, this.speed); + } + + public void send() { + WebSocketMessageSingleton.getInstance().sendToAll( + this.toWebsocketMessage() + ); + } } diff --git a/src/main/java/telraam/logic/positioner/SimplePositioner.java b/src/main/java/telraam/logic/positioner/SimplePositioner.java index 83d2872..794fa35 100644 --- a/src/main/java/telraam/logic/positioner/SimplePositioner.java +++ b/src/main/java/telraam/logic/positioner/SimplePositioner.java @@ -1,4 +1,4 @@ -package telraam.logic.positioners; +package telraam.logic.positioner; import org.jdbi.v3.core.Jdbi; import telraam.database.daos.BatonSwitchoverDAO; diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index 54e04db..d2cdce0 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -7,7 +7,7 @@ import telraam.database.models.Baton; import telraam.database.models.Detection; import telraam.database.models.Station; -import telraam.logic.Lapper; +import telraam.logic.lapper.Lapper; import telraam.station.models.RonnyDetection; import telraam.station.models.RonnyResponse; diff --git a/src/test/java/telraam/logic/simple/SimpleLapperTest.java b/src/test/java/telraam/logic/simple/SimpleLapperTest.java index 838397f..c50e810 100644 --- a/src/test/java/telraam/logic/simple/SimpleLapperTest.java +++ b/src/test/java/telraam/logic/simple/SimpleLapperTest.java @@ -8,8 +8,8 @@ import telraam.database.models.Detection; import telraam.database.models.Lap; import telraam.database.models.LapSource; -import telraam.logic.Lapper; -import telraam.logic.simple.SimpleLapper; +import telraam.logic.lapper.Lapper; +import telraam.logic.lapper.simple.SimpleLapper; import java.sql.Timestamp; import java.util.Optional; From 2262cbb09e7016158a6b9534b033dca6fa25e5be Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 13:46:19 +0100 Subject: [PATCH 39/90] implementation of positioner --- src/main/java/telraam/App.java | 9 +- .../telraam/logic/positioner/Position.java | 18 +-- .../logic/positioner/PositionSender.java | 31 ++++++ .../telraam/logic/positioner/Positioner.java | 9 ++ .../logic/positioner/SimplePositioner.java | 66 ----------- .../positioner/simple/SimplePositioner.java | 104 ++++++++++++++++++ src/main/java/telraam/station/Fetcher.java | 10 +- .../telraam/websocket/WebSocketMessage.java | 10 ++ .../websocket/WebSocketMessageSingleton.java | 19 +++- 9 files changed, 190 insertions(+), 86 deletions(-) create mode 100644 src/main/java/telraam/logic/positioner/PositionSender.java create mode 100644 src/main/java/telraam/logic/positioner/Positioner.java delete mode 100644 src/main/java/telraam/logic/positioner/SimplePositioner.java create mode 100644 src/main/java/telraam/logic/positioner/simple/SimplePositioner.java create mode 100644 src/main/java/telraam/websocket/WebSocketMessage.java diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 5c93fe8..4e6eb03 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -20,6 +20,8 @@ import telraam.logic.lapper.Lapper; import telraam.logic.lapper.external.ExternalLapper; import telraam.logic.lapper.robust.RobustLapper; +import telraam.logic.positioner.Positioner; +import telraam.logic.positioner.simple.SimplePositioner; import telraam.station.Fetcher; import telraam.util.AcceptedLapsUtil; import telraam.websocket.WebSocketConnection; @@ -131,10 +133,15 @@ public void run(AppConfiguration configuration, Environment environment) throws lapper.registerAPI(jersey); } + // Set up positioners + Set positioners = new HashSet<>(); + + positioners.add(new SimplePositioner(this.database)); + // Start fetch thread for each station StationDAO stationDAO = this.database.onDemand(StationDAO.class); for (Station station : stationDAO.getAll()) { - new Thread(() -> new Fetcher(this.database, station, lappers).fetch()).start(); + new Thread(() -> new Fetcher(this.database, station, lappers, positioners).fetch()).start(); } } diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 23bcf00..3a4218e 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -1,4 +1,4 @@ -package telraam.logic.positioners; +package telraam.logic.positioner; import lombok.Getter; import lombok.Setter; @@ -7,23 +7,13 @@ @Getter @Setter public class Position { - private Team team; + private int teamId; private float progress; // Progress of the lap. Between 0-1 private float speed; // Current speed. Progress / second - public Position(Team team) { - this.team = team; + public Position(int teamId) { + this.teamId = teamId; this.progress = 0; this.speed = 0; } - - private String toWebsocketMessage() { - return String.format("{\"topic\": \"position\", \"data\": {\"team\": %d, \"progress\": %.4f, \"speed\": %.5f}}", team.getId(), this.progress, this.speed); - } - - public void send() { - WebSocketMessageSingleton.getInstance().sendToAll( - this.toWebsocketMessage() - ); - } } diff --git a/src/main/java/telraam/logic/positioner/PositionSender.java b/src/main/java/telraam/logic/positioner/PositionSender.java new file mode 100644 index 0000000..e6fe68d --- /dev/null +++ b/src/main/java/telraam/logic/positioner/PositionSender.java @@ -0,0 +1,31 @@ +package telraam.logic.positioner; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.NoArgsConstructor; +import telraam.websocket.WebSocketMessage; +import telraam.websocket.WebSocketMessageSingleton; + +import java.util.List; +import java.util.logging.Logger; + +public class PositionSender { + private static final Logger logger = Logger.getLogger(PositionSender.class.getName()); + private final ObjectMapper mapper = new ObjectMapper(); + private final WebSocketMessage message = new WebSocketMessage(); + + public PositionSender() { + this.message.setTopic("position"); + } + + public void send(List position) { + try { + String json = mapper.writeValueAsString(position); + this.message.setData(json); + WebSocketMessageSingleton.getInstance().sendToAll(this.message); + } catch (JsonProcessingException e) { + logger.severe("Json conversion error for \"%s\"".formatted(position.toString())); + } + } + +} diff --git a/src/main/java/telraam/logic/positioner/Positioner.java b/src/main/java/telraam/logic/positioner/Positioner.java new file mode 100644 index 0000000..b61cdbf --- /dev/null +++ b/src/main/java/telraam/logic/positioner/Positioner.java @@ -0,0 +1,9 @@ +package telraam.logic.positioner; + +import telraam.database.models.Detection; + +public interface Positioner { + void handle(Detection detection); + + void calculatePositions(); +} diff --git a/src/main/java/telraam/logic/positioner/SimplePositioner.java b/src/main/java/telraam/logic/positioner/SimplePositioner.java deleted file mode 100644 index 794fa35..0000000 --- a/src/main/java/telraam/logic/positioner/SimplePositioner.java +++ /dev/null @@ -1,66 +0,0 @@ -package telraam.logic.positioner; - -import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonSwitchoverDAO; -import telraam.database.daos.StationDAO; -import telraam.database.daos.TeamDAO; -import telraam.database.models.BatonSwitchover; -import telraam.database.models.Detection; -import telraam.database.models.Station; -import telraam.database.models.Team; - -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class SimplePositioner { - private final int QUEUE_SIZE = 50; - private final int MIN_RSSI = -85; - private Map teamIdToTeam = new HashMap<>(); - private Map> teamDetections = new HashMap<>(); - private List stations; - - public SimplePositioner(Jdbi jdbi) { - TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); - List teams = teamDAO.getAll(); - for (Team team: teams) { - this.teamDetections.put(team, new CircularQueue<>(QUEUE_SIZE)); - } - List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); - switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); - - for (BatonSwitchover switchover: switchovers) { - this.teamIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); - } - - List stationList = jdbi.onDemand(StationDAO.class).getAll(); - stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); - this.stations = stationList.stream().map(Station::getId).toList(); - } - - private void calculatePosition(Team team) { - List detections = this.teamDetections.get(team); - detections.sort(Comparator.comparing(Detection::getTimestamp)); - - int currentStationRssi = MIN_RSSI; - int currentStationPosition = 0; - for (Detection detection: detections) { - if (detection.getRssi() > currentStationRssi) { - currentStationRssi = detection.getRssi(); - currentStationPosition = detection.getStationId(); - } - } - - float progress = ((float) 100 / this.stations.size()) * this.stations.indexOf(currentStationPosition); - - System.out.printf("Team: %s | Progress: %f | Acceleration: %f%n", team.getName(), progress, 1.0); - } - - public void handle(Detection detection) { - Team team = this.teamIdToTeam.get(detection.getBatonId()); - this.teamDetections.get(team).add(detection); - this.calculatePosition(team); - } - -} diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java new file mode 100644 index 0000000..f8a9022 --- /dev/null +++ b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java @@ -0,0 +1,104 @@ +package telraam.logic.positioner.simple; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.BatonSwitchover; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.database.models.Team; +import telraam.logic.positioner.CircularQueue; +import telraam.logic.positioner.Position; +import telraam.logic.positioner.PositionSender; +import telraam.logic.positioner.Positioner; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +public class SimplePositioner implements Positioner { + private final int QUEUE_SIZE = 50; + private final int MIN_RSSI = -85; + private final int DEBOUNCE_TIMEOUT = 1; + private boolean debounceScheduled; + private final ScheduledExecutorService scheduler; + private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); + private final PositionSender positionSender; + private final Map batonIdToTeam; + private final Map> teamDetections; + private final List stations; + private final Map teamPositions; + + public SimplePositioner(Jdbi jdbi) { + this.debounceScheduled = false; + this.scheduler = Executors.newScheduledThreadPool(1); + this.positionSender = new PositionSender(); + this.batonIdToTeam = new HashMap<>(); + this.teamDetections = new HashMap<>(); + this.teamPositions = new HashMap<>(); + + TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); + List teams = teamDAO.getAll(); + for (Team team: teams) { + teamDetections.put(team, new CircularQueue<>(QUEUE_SIZE)); + teamPositions.put(team, new Position(team.getId())); + } + List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); + switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); + + for (BatonSwitchover switchover: switchovers) { + batonIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); + } + + List stationList = jdbi.onDemand(StationDAO.class).getAll(); + stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); + stations = stationList.stream().map(Station::getId).toList(); + } + + public void calculatePositions() { + logger.info("SimplePositioner: Calculating positions..."); + for (Map.Entry> entry: teamDetections.entrySet()) { + List detections = teamDetections.get(entry.getKey()); + detections.sort(Comparator.comparing(Detection::getTimestamp)); + + int currentStationRssi = MIN_RSSI; + int currentStationPosition = 0; + for (Detection detection: detections) { + if (detection.getRssi() > currentStationRssi) { + currentStationRssi = detection.getRssi(); + currentStationPosition = detection.getStationId(); + } + } + + float progress = ((float) 100 / stations.size()) * currentStationPosition; + teamPositions.get(entry.getKey()).setProgress(progress); + } + + positionSender.send(teamPositions.values().stream().toList()); + logger.info("SimplePositioner: Done calculating positions"); + } + + public void handle(Detection detection) { + Team team = batonIdToTeam.get(detection.getBatonId()); + teamDetections.get(team).add(detection); + + if (! debounceScheduled) { + debounceScheduled = true; + scheduler.schedule(() -> { + try { + calculatePositions(); + } catch (Exception e) { + logger.severe(e.getMessage()); + } + debounceScheduled = false; + }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); + } + } + +} diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index d2cdce0..bb0ed5e 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -8,6 +8,7 @@ import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.logic.lapper.Lapper; +import telraam.logic.positioner.Positioner; import telraam.station.models.RonnyDetection; import telraam.station.models.RonnyResponse; @@ -29,6 +30,7 @@ public class Fetcher { private final Set lappers; + private final Set positioners; private Station station; private final BatonDAO batonDAO; @@ -48,11 +50,12 @@ public class Fetcher { private final static int IDLE_TIMEOUT_MS = 4000; // Wait 4 seconds - public Fetcher(Jdbi database, Station station, Set lappers) { + public Fetcher(Jdbi database, Station station, Set lappers, Set positioners) { this.batonDAO = database.onDemand(BatonDAO.class); this.detectionDAO = database.onDemand(DetectionDAO.class); this.stationDAO = database.onDemand(StationDAO.class); this.lappers = lappers; + this.positioners = positioners; this.station = station; } @@ -158,7 +161,10 @@ public void fetch() { } if (!new_detections.isEmpty()) { detectionDAO.insertAll(new_detections); - new_detections.forEach((detection) -> lappers.forEach((lapper) -> lapper.handle(detection))); + new_detections.forEach((detection) -> { + lappers.forEach((lapper) -> lapper.handle(detection)); + positioners.forEach((positioner) -> positioner.handle(detection)); + }); } this.logger.finer("Fetched " + detections.size() + " detections from " + station.getName() + ", Saved " + new_detections.size()); diff --git a/src/main/java/telraam/websocket/WebSocketMessage.java b/src/main/java/telraam/websocket/WebSocketMessage.java new file mode 100644 index 0000000..67cf878 --- /dev/null +++ b/src/main/java/telraam/websocket/WebSocketMessage.java @@ -0,0 +1,10 @@ +package telraam.websocket; + +import lombok.Getter; +import lombok.Setter; + +@Getter @Setter +public class WebSocketMessage { + private String topic; + private String data; +} diff --git a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java index de12115..598a901 100644 --- a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java +++ b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java @@ -1,20 +1,24 @@ package telraam.websocket; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; +import lombok.NoArgsConstructor; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; +@NoArgsConstructor public class WebSocketMessageSingleton { private static final Logger logger = Logger.getLogger(WebSocketMessageSingleton.class.getName()); @Getter private static final WebSocketMessageSingleton instance = new WebSocketMessageSingleton(); private static final Set registeredConnections = new HashSet<>(); - - private WebSocketMessageSingleton() { - } + private ObjectMapper mapper = new ObjectMapper(); public void registerConnection(WebSocketConnection conn) { boolean modified = registeredConnections.add(conn); @@ -34,4 +38,13 @@ public void sendToAll(String s) { logger.finest("Sending \"%s\" to all registered WebSocketConnection instances".formatted(s)); registeredConnections.forEach(conn -> conn.send(s)); } + + public void sendToAll(WebSocketMessage message) { + try { + String json = mapper.writeValueAsString(message); + this.sendToAll(json); + } catch (JsonProcessingException e) { + logger.severe("Json conversion error for \"%s\"".formatted(message.toString())); + } + } } From c173bebf295ac8f7e6eaf667142adb13046a3b15 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 14:01:57 +0100 Subject: [PATCH 40/90] cleanup --- src/main/java/telraam/logic/positioner/CircularQueue.java | 2 +- src/main/java/telraam/logic/positioner/Positioner.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/CircularQueue.java b/src/main/java/telraam/logic/positioner/CircularQueue.java index 042ba79..94cadec 100644 --- a/src/main/java/telraam/logic/positioner/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/CircularQueue.java @@ -14,7 +14,7 @@ public CircularQueue(int maxSize) { @Override public boolean add(T e) { if (this.size >= this.maxSize) { - super.removeFirst(); + removeFirst(); this.size--; } diff --git a/src/main/java/telraam/logic/positioner/Positioner.java b/src/main/java/telraam/logic/positioner/Positioner.java index b61cdbf..4128b36 100644 --- a/src/main/java/telraam/logic/positioner/Positioner.java +++ b/src/main/java/telraam/logic/positioner/Positioner.java @@ -5,5 +5,4 @@ public interface Positioner { void handle(Detection detection); - void calculatePositions(); } From f6aab9f53f5badcdb9393865c2c47becad53cafa Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 14:18:09 +0100 Subject: [PATCH 41/90] change WebSocketMessage data type --- .../logic/positioner/PositionSender.java | 19 ++++--------------- .../telraam/websocket/WebSocketMessage.java | 4 ++-- .../websocket/WebSocketMessageSingleton.java | 4 ++-- 3 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/PositionSender.java b/src/main/java/telraam/logic/positioner/PositionSender.java index e6fe68d..5e779dc 100644 --- a/src/main/java/telraam/logic/positioner/PositionSender.java +++ b/src/main/java/telraam/logic/positioner/PositionSender.java @@ -1,31 +1,20 @@ package telraam.logic.positioner; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.NoArgsConstructor; import telraam.websocket.WebSocketMessage; import telraam.websocket.WebSocketMessageSingleton; import java.util.List; -import java.util.logging.Logger; public class PositionSender { - private static final Logger logger = Logger.getLogger(PositionSender.class.getName()); - private final ObjectMapper mapper = new ObjectMapper(); - private final WebSocketMessage message = new WebSocketMessage(); + private final WebSocketMessage> message = new WebSocketMessage<>(); public PositionSender() { this.message.setTopic("position"); } - public void send(List position) { - try { - String json = mapper.writeValueAsString(position); - this.message.setData(json); - WebSocketMessageSingleton.getInstance().sendToAll(this.message); - } catch (JsonProcessingException e) { - logger.severe("Json conversion error for \"%s\"".formatted(position.toString())); - } + public void send(List positions) { + this.message.setData(positions); + WebSocketMessageSingleton.getInstance().sendToAll(this.message); } } diff --git a/src/main/java/telraam/websocket/WebSocketMessage.java b/src/main/java/telraam/websocket/WebSocketMessage.java index 67cf878..0b4200f 100644 --- a/src/main/java/telraam/websocket/WebSocketMessage.java +++ b/src/main/java/telraam/websocket/WebSocketMessage.java @@ -4,7 +4,7 @@ import lombok.Setter; @Getter @Setter -public class WebSocketMessage { +public class WebSocketMessage { private String topic; - private String data; + private T data; } diff --git a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java index 598a901..d073217 100644 --- a/src/main/java/telraam/websocket/WebSocketMessageSingleton.java +++ b/src/main/java/telraam/websocket/WebSocketMessageSingleton.java @@ -18,7 +18,7 @@ public class WebSocketMessageSingleton { @Getter private static final WebSocketMessageSingleton instance = new WebSocketMessageSingleton(); private static final Set registeredConnections = new HashSet<>(); - private ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); public void registerConnection(WebSocketConnection conn) { boolean modified = registeredConnections.add(conn); @@ -39,7 +39,7 @@ public void sendToAll(String s) { registeredConnections.forEach(conn -> conn.send(s)); } - public void sendToAll(WebSocketMessage message) { + public void sendToAll(WebSocketMessage message) { try { String json = mapper.writeValueAsString(message); this.sendToAll(json); From f71ad1ba1f9e0c4791352ffbe09553693d8fcede Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 29 Mar 2024 14:21:09 +0100 Subject: [PATCH 42/90] use built in function --- .../telraam/logic/positioner/CircularQueue.java | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/CircularQueue.java b/src/main/java/telraam/logic/positioner/CircularQueue.java index 94cadec..773c633 100644 --- a/src/main/java/telraam/logic/positioner/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/CircularQueue.java @@ -5,26 +5,17 @@ public class CircularQueue extends LinkedList { private final int maxSize; - private int size = 0; - public CircularQueue(int maxSize) { this.maxSize = maxSize; } @Override public boolean add(T e) { - if (this.size >= this.maxSize) { + if (size() >= this.maxSize) { removeFirst(); - this.size--; - } - - boolean result = super.add(e); - - if (result) { - this.size++; } - return result; + return super.add(e); } } From 7bd44a4e22a787fa8e9fcfce27be427b8659000d Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Fri, 29 Mar 2024 14:47:57 +0100 Subject: [PATCH 43/90] yeet :eyes: --- .../telraam/api/AbstractListableResource.java | 2 + .../java/telraam/api/AbstractResource.java | 6 +++ src/main/java/telraam/api/BatonResource.java | 38 +----------------- .../telraam/api/BatonSwitchoverResource.java | 24 +---------- .../java/telraam/api/DetectionResource.java | 30 -------------- src/main/java/telraam/api/LapResource.java | 24 ----------- .../java/telraam/api/LapSourceResource.java | 37 +---------------- .../api/LapSourceSwitchoverResource.java | 27 ++----------- .../java/telraam/api/StationResource.java | 40 ++----------------- src/main/java/telraam/api/TeamResource.java | 18 --------- src/main/java/telraam/api/TimeResource.java | 2 +- 11 files changed, 20 insertions(+), 228 deletions(-) diff --git a/src/main/java/telraam/api/AbstractListableResource.java b/src/main/java/telraam/api/AbstractListableResource.java index e600a1c..b9e5030 100644 --- a/src/main/java/telraam/api/AbstractListableResource.java +++ b/src/main/java/telraam/api/AbstractListableResource.java @@ -1,6 +1,7 @@ package telraam.api; +import io.swagger.v3.oas.annotations.Operation; import telraam.database.daos.DAO; import java.util.List; @@ -11,6 +12,7 @@ protected AbstractListableResource(DAO dao) { } @Override + @Operation(summary = "Find all") public List getListOf() { return dao.getAll(); } diff --git a/src/main/java/telraam/api/AbstractResource.java b/src/main/java/telraam/api/AbstractResource.java index bcd70d0..62f9bd7 100644 --- a/src/main/java/telraam/api/AbstractResource.java +++ b/src/main/java/telraam/api/AbstractResource.java @@ -1,11 +1,13 @@ package telraam.api; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.ws.rs.GET; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Response; +import org.checkerframework.checker.units.qual.C; import telraam.database.daos.DAO; import java.util.Optional; @@ -19,12 +21,14 @@ protected AbstractResource(DAO dao) { } @Override + @Operation(summary = "Add new to the database") // TODO Validate model and return 405 for wrong input public int create(@Parameter(required = true) T t) { return dao.insert(t); } @Override + @Operation(summary = "Find by ID") @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied") // TODO validate ID, return 400 on wrong ID format @ApiResponse(responseCode = "404", description = "Entity with specified ID not found") public T get(@Parameter(description = "ID of entity that needs to be fetched", required = true) Optional id) { @@ -41,6 +45,7 @@ public T get(@Parameter(description = "ID of entity that needs to be fetched", r } @Override + @Operation(summary = "Update an existing") @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied") // TODO validate ID, return 400 on wrong ID format @ApiResponse(responseCode = "404", description = "Entity with specified ID not found") @ApiResponse(responseCode = "405", description = "Validation exception") // TODO validate input, 405 on wrong input @@ -60,6 +65,7 @@ public T update(@Parameter(description = "Entity object that needs to be updated } @Override + @Operation(summary = "Delete an existing") @ApiResponses(value = { @ApiResponse(responseCode = "400", description = "Invalid or no ID supplied"), // TODO validate ID, return 400 on wrong ID format }) diff --git a/src/main/java/telraam/api/BatonResource.java b/src/main/java/telraam/api/BatonResource.java index 49bcd68..faa802b 100644 --- a/src/main/java/telraam/api/BatonResource.java +++ b/src/main/java/telraam/api/BatonResource.java @@ -1,52 +1,18 @@ package telraam.api; -import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; -import telraam.database.daos.BatonDAO; +import telraam.database.daos.DAO; import telraam.database.models.Baton; -import java.util.List; -import java.util.Optional; - @Path("/baton") // dropwizard @Tag(name = "Baton") @Produces(MediaType.APPLICATION_JSON) public class BatonResource extends AbstractListableResource { - public BatonResource(BatonDAO dao) { + public BatonResource(DAO dao) { super(dao); } - - @Override - @Operation(summary = "Find all batons") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Add a new baton to the database") - public int create(Baton baton) { - return super.create(baton); - } - - @Override - @Operation(summary = "Find baton by ID") - public Baton get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Update an existing baton") - public Baton update(Baton baton, Optional id) { - return super.update(baton, id); - } - - @Override - @Operation(summary = "Delete an existing baton") - public boolean delete(Optional id) { - return super.delete(id); - } } diff --git a/src/main/java/telraam/api/BatonSwitchoverResource.java b/src/main/java/telraam/api/BatonSwitchoverResource.java index 72a0b85..9b1a173 100644 --- a/src/main/java/telraam/api/BatonSwitchoverResource.java +++ b/src/main/java/telraam/api/BatonSwitchoverResource.java @@ -1,6 +1,5 @@ package telraam.api; -import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; @@ -8,33 +7,12 @@ import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.models.BatonSwitchover; -import java.util.List; -import java.util.Optional; - @Path("/batonswitchover") // dropwizard -@Tag(name="Baton Switchover") +@Tag(name = "Baton Switchover") @Produces(MediaType.APPLICATION_JSON) public class BatonSwitchoverResource extends AbstractListableResource { public BatonSwitchoverResource(BatonSwitchoverDAO dao) { super(dao); } - - @Override - @Operation(summary = "Find all baton switchovers") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Find baton switchover by ID") - public BatonSwitchover get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Add a new baton switchover to the database") - public int create(BatonSwitchover batonSwitchover) { - return super.create(batonSwitchover); - } } diff --git a/src/main/java/telraam/api/DetectionResource.java b/src/main/java/telraam/api/DetectionResource.java index c41a514..b7566cc 100644 --- a/src/main/java/telraam/api/DetectionResource.java +++ b/src/main/java/telraam/api/DetectionResource.java @@ -22,36 +22,6 @@ public DetectionResource(DetectionDAO dao) { detectionDAO = dao; } - @Override - @Operation(summary = "Find all detections") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Add a new detection to the database") - public int create(Detection detection) { - return super.create(detection); - } - - @Override - @Operation(summary = "Find detection by ID") - public Detection get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Update an existing detection") - public Detection update(Detection detection, Optional id) { - return super.update(detection, id); - } - - @Override - @Operation(summary = "Delete an existing detection") - public boolean delete(Optional id) { - return super.delete(id); - } - @GET @Path("/since/{id}") @Operation(summary = "Get detections with ID larger than given ID") diff --git a/src/main/java/telraam/api/LapResource.java b/src/main/java/telraam/api/LapResource.java index 25da4b9..a0ef3db 100644 --- a/src/main/java/telraam/api/LapResource.java +++ b/src/main/java/telraam/api/LapResource.java @@ -30,28 +30,4 @@ public List getListOf(@QueryParam("source") final Integer source) { return lapDAO.getAllBySource(source); } } - - @Override - @Operation(summary = "Add a new lap to the database") - public int create(Lap lap) { - return super.create(lap); - } - - @Override - @Operation(summary = "Find lap by ID") - public Lap get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Update an existing lap") - public Lap update(Lap lap, Optional id) { - return super.update(lap, id); - } - - @Override - @Operation(summary = "Delete an existing lap") - public boolean delete(Optional id) { - return super.delete(id); - } } diff --git a/src/main/java/telraam/api/LapSourceResource.java b/src/main/java/telraam/api/LapSourceResource.java index bed07ac..630e6db 100644 --- a/src/main/java/telraam/api/LapSourceResource.java +++ b/src/main/java/telraam/api/LapSourceResource.java @@ -1,15 +1,12 @@ package telraam.api; -import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import telraam.database.daos.DAO; import telraam.database.models.LapSource; -import java.util.List; -import java.util.Optional; - @Path("/lap-source") @Tag(name = "Lap Source") @Produces(MediaType.APPLICATION_JSON) @@ -17,34 +14,4 @@ public class LapSourceResource extends AbstractListableResource { public LapSourceResource(DAO dao) { super(dao); } - - @Override - @Operation(summary = "Find all lap sources") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Add a new lap source to the database") - public int create(LapSource lapSource) { - return super.create(lapSource); - } - - @Override - @Operation(summary = "Find lap source by ID") - public LapSource get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Update an existing lap source") - public LapSource update(LapSource lapSource, Optional id) { - return super.update(lapSource, id); - } - - @Override - @Operation(summary = "Delete an existing lap source") - public boolean delete(Optional id) { - return super.delete(id); - } } diff --git a/src/main/java/telraam/api/LapSourceSwitchoverResource.java b/src/main/java/telraam/api/LapSourceSwitchoverResource.java index 9ad4d1f..598cdf0 100644 --- a/src/main/java/telraam/api/LapSourceSwitchoverResource.java +++ b/src/main/java/telraam/api/LapSourceSwitchoverResource.java @@ -1,39 +1,18 @@ package telraam.api; -import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import telraam.database.daos.LapSourceSwitchoverDAO; import telraam.database.models.LapSourceSwitchover; -import java.util.List; -import java.util.Optional; - @Path("/lapsourceswitchover") // dropwizard -@Tag(name="Lap Source Switchover") +@Tag(name = "Lap Source Switchover") @Produces(MediaType.APPLICATION_JSON) public class LapSourceSwitchoverResource extends AbstractListableResource { public LapSourceSwitchoverResource(LapSourceSwitchoverDAO dao) { super(dao); } - - @Override - @Operation(summary = "Find all lap source switchovers") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Find lap source switchover by ID") - public LapSourceSwitchover get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Add a new lap source switchover to the database") - public int create(LapSourceSwitchover lapSourceSwitchover) { - return super.create(lapSourceSwitchover); - } } diff --git a/src/main/java/telraam/api/StationResource.java b/src/main/java/telraam/api/StationResource.java index df61deb..106131c 100644 --- a/src/main/java/telraam/api/StationResource.java +++ b/src/main/java/telraam/api/StationResource.java @@ -1,51 +1,17 @@ package telraam.api; -import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import telraam.database.daos.DAO; import telraam.database.models.Station; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.core.MediaType; -import java.util.List; -import java.util.Optional; - @Path("/station") -@Tag(name="Station") +@Tag(name = "Station") @Produces(MediaType.APPLICATION_JSON) public class StationResource extends AbstractListableResource { public StationResource(DAO dao) { super(dao); } - - @Override - @Operation(summary = "Find all stations") - public List getListOf() { - return super.getListOf(); - } - - @Override - @Operation(summary = "Add a new station to the database") - public int create(Station station) { - return super.create(station); - } - - @Override - @Operation(summary = "Find station by ID") - public Station get(Optional id) { - return super.get(id); - } - - @Override - @Operation(summary = "Update an existing station") - public Station update(Station station, Optional id) { - return super.update(station, id); - } - - @Override - @Operation(summary = "Delete an existing station") - public boolean delete(Optional id) { - return super.delete(id); - } } diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 56975c9..5983eff 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -28,12 +28,6 @@ public TeamResource(TeamDAO teamDAO, BatonSwitchoverDAO batonSwitchoverDAO) { this.batonSwitchoverDAO = batonSwitchoverDAO; } - @Override - @Operation(summary = "Find all teams") - public List getListOf() { - return super.getListOf(); - } - @Override @Operation(summary = "Add a new team to the database") public int create(Team team) { @@ -51,12 +45,6 @@ public int create(Team team) { return ret; } - @Override - @Operation(summary = "Find team by ID") - public Team get(Optional id) { - return super.get(id); - } - @Override @Operation(summary = "Update an existing team") public Team update(Team team, Optional id) { @@ -77,10 +65,4 @@ public Team update(Team team, Optional id) { return ret; } - - @Override - @Operation(summary = "Delete an existing team") - public boolean delete(Optional id) { - return super.delete(id); - } } diff --git a/src/main/java/telraam/api/TimeResource.java b/src/main/java/telraam/api/TimeResource.java index ebdae5f..f49e0c3 100644 --- a/src/main/java/telraam/api/TimeResource.java +++ b/src/main/java/telraam/api/TimeResource.java @@ -11,7 +11,7 @@ @Tag(name = "Time") @Produces(MediaType.APPLICATION_JSON) public class TimeResource { - static class TimeResponse { + public static class TimeResponse { public long timestamp; public TimeResponse() { From d94f7307e228c5ccd363879d67a214fe30ed21a2 Mon Sep 17 00:00:00 2001 From: FKD13 <44001949+FKD13@users.noreply.github.com> Date: Fri, 29 Mar 2024 16:22:25 +0100 Subject: [PATCH 44/90] apply even more lombok --- src/main/java/telraam/App.java | 33 +++----- src/main/java/telraam/AppConfiguration.java | 46 ++-------- .../java/telraam/api/responses/Saying.java | 26 ++---- .../java/telraam/api/responses/Template.java | 8 +- .../monitoring/BatonDetectionManager.java | 10 +-- .../telraam/monitoring/BatonStatusHolder.java | 14 ++-- .../monitoring/StationDetectionManager.java | 6 +- .../monitoring/models/BatonDetection.java | 54 ++---------- .../monitoring/models/BatonStatus.java | 83 ++----------------- .../monitoring/models/LapCountForTeam.java | 9 +- .../monitoring/models/TeamLapInfo.java | 13 ++- src/main/java/telraam/station/Fetcher.java | 2 +- .../websocket/WebSocketMessageSingleton.java | 4 +- 13 files changed, 70 insertions(+), 238 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 4e6eb03..5b1644e 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -10,6 +10,8 @@ import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration; import jakarta.servlet.DispatcherType; import jakarta.servlet.FilterRegistration; +import lombok.Getter; +import lombok.Setter; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.jdbi.v3.core.Jdbi; @@ -33,10 +35,18 @@ import java.util.logging.Logger; public class App extends Application { - private static Logger logger = Logger.getLogger(App.class.getName()); + private static final Logger logger = Logger.getLogger(App.class.getName()); + + @Getter private AppConfiguration config; + + @Getter private Environment environment; + + @Getter private Jdbi database; + + @Setter private boolean testing; public static void main(String[] args) throws Exception { @@ -49,10 +59,6 @@ public App() { testing = true; } - public void setTesting(boolean testing) { - this.testing = testing; - } - @Override public String getName() { return "hello-world"; @@ -72,7 +78,7 @@ protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(AppConfigurat } @Override - public void run(AppConfiguration configuration, Environment environment) throws IOException { + public void run(AppConfiguration configuration, Environment environment) { this.config = configuration; this.environment = environment; // Add database @@ -122,9 +128,6 @@ public void run(AppConfiguration configuration, Environment environment) throws // Set up lapper algorithms Set lappers = new HashSet<>(); - // Old viterbi lapper is disabled - //lappers.add(new ViterbiLapper(this.database)); - lappers.add(new ExternalLapper(this.database)); lappers.add(new RobustLapper(this.database)); @@ -147,16 +150,4 @@ public void run(AppConfiguration configuration, Environment environment) throws logger.info("Up and running!"); } - - public AppConfiguration getConfig() { - return config; - } - - public Environment getEnvironment() { - return environment; - } - - public Jdbi getDatabase() { - return database; - } } diff --git a/src/main/java/telraam/AppConfiguration.java b/src/main/java/telraam/AppConfiguration.java index 15eefbc..c338c65 100644 --- a/src/main/java/telraam/AppConfiguration.java +++ b/src/main/java/telraam/AppConfiguration.java @@ -6,53 +6,25 @@ import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; import telraam.api.responses.Template; public class AppConfiguration extends Configuration { @NotNull + @Getter @Setter private String template; @NotNull + @Getter @Setter private String defaultName = "Stranger"; + @JsonProperty("swagger") + public SwaggerBundleConfiguration swaggerBundleConfiguration; + @Valid @NotNull - private DataSourceFactory database = new DataSourceFactory(); - - @JsonProperty - public String getTemplate() { - return template; - } - - @JsonProperty - public void setTemplate(String template) { - this.template = template; - } - - public Template buildTemplate() { - return new Template(template, defaultName); - } - - @JsonProperty - public String getDefaultName() { - return defaultName; - } - - @JsonProperty - public void setDefaultName(String name) { - this.defaultName = name; - } - - @JsonProperty("database") - public DataSourceFactory getDataSourceFactory() { - return database; - } - + @Getter @Setter @JsonProperty("database") - public void setDataSourceFactory(DataSourceFactory factory) { - this.database = factory; - } - - @JsonProperty("swagger") - public SwaggerBundleConfiguration swaggerBundleConfiguration; + private DataSourceFactory dataSourceFactory = new DataSourceFactory(); } diff --git a/src/main/java/telraam/api/responses/Saying.java b/src/main/java/telraam/api/responses/Saying.java index 79afdf9..5750eea 100644 --- a/src/main/java/telraam/api/responses/Saying.java +++ b/src/main/java/telraam/api/responses/Saying.java @@ -1,30 +1,16 @@ package telraam.api.responses; -import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.Length; +@Getter +@NoArgsConstructor +@AllArgsConstructor public class Saying { private long id; @Length(max = 3) private String content; - - public Saying() { - // Jackson deserialization - } - - public Saying(long id, String content) { - this.id = id; - this.content = content; - } - - @JsonProperty - public long getId() { - return id; - } - - @JsonProperty - public String getContent() { - return content; - } } \ No newline at end of file diff --git a/src/main/java/telraam/api/responses/Template.java b/src/main/java/telraam/api/responses/Template.java index ce15c84..d41829d 100644 --- a/src/main/java/telraam/api/responses/Template.java +++ b/src/main/java/telraam/api/responses/Template.java @@ -1,18 +1,16 @@ package telraam.api.responses; +import lombok.AllArgsConstructor; + import java.util.Optional; import static java.lang.String.format; +@AllArgsConstructor public class Template { private final String content; private final String defaultName; - public Template(String content, String defaultName) { - this.content = content; - this.defaultName = defaultName; - } - public String render(Optional name) { return format(content, name.orElse(defaultName)); } diff --git a/src/main/java/telraam/monitoring/BatonDetectionManager.java b/src/main/java/telraam/monitoring/BatonDetectionManager.java index db6b10b..f48dafd 100644 --- a/src/main/java/telraam/monitoring/BatonDetectionManager.java +++ b/src/main/java/telraam/monitoring/BatonDetectionManager.java @@ -12,12 +12,12 @@ import java.util.Map; public class BatonDetectionManager { - private DetectionDAO detectionDAO; - private TeamDAO teamDAO; - private BatonSwitchoverDAO batonSwitchoverDAO; + private final DetectionDAO detectionDAO; + private final TeamDAO teamDAO; + private final BatonSwitchoverDAO batonSwitchoverDAO; // Map of a baton id to it's detections - private Map> batonDetectionMap = new HashMap<>(); + private final Map> batonDetectionMap = new HashMap<>(); private Integer handledDetectionId = 0; public BatonDetectionManager(DetectionDAO detectionDAO, TeamDAO teamDAO, BatonSwitchoverDAO batonSwitchoverDAO) { @@ -60,7 +60,7 @@ public Map> getBatonDetections() { } var batonDetections = batonDetectionMap.get(batonId); var team = teamMap.get(batonTeamMap.get(batonId)); - var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), d.getStationId(), batonId, team.getName()); + var batonDetection = new BatonDetection(Math.toIntExact(d.getTimestamp().getTime() / 1000), d.getRssi(), batonId /* FIXME: BatonDetection expects a teamId here? */, d.getStationId(), team.getName()); batonDetections.add(batonDetection); }); return batonDetectionMap; diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java index b791e0e..ea2d39c 100644 --- a/src/main/java/telraam/monitoring/BatonStatusHolder.java +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -15,15 +15,15 @@ public class BatonStatusHolder { // Map from batonMac to batonStatus - private HashMap batonStatusMap = new HashMap<>(); - private HashMap batonIdToMac = new HashMap<>(); + private final HashMap batonStatusMap = new HashMap<>(); + private final HashMap batonIdToMac = new HashMap<>(); - private BatonDAO batonDAO; - private DetectionDAO detectionDAO; + private final BatonDAO batonDAO; + private final DetectionDAO detectionDAO; - public BatonStatusHolder(BatonDAO BDAO, DetectionDAO DDAO) { - batonDAO = BDAO; - detectionDAO = DDAO; + public BatonStatusHolder(BatonDAO batonDAO, DetectionDAO detectionDAO) { + this.batonDAO = batonDAO; + this.detectionDAO = detectionDAO; } private BatonStatus getStatusForBaton(String batonMac) { diff --git a/src/main/java/telraam/monitoring/StationDetectionManager.java b/src/main/java/telraam/monitoring/StationDetectionManager.java index 3929f42..931883f 100644 --- a/src/main/java/telraam/monitoring/StationDetectionManager.java +++ b/src/main/java/telraam/monitoring/StationDetectionManager.java @@ -11,9 +11,9 @@ import java.util.Optional; public class StationDetectionManager { - private DetectionDAO detectionDAO; + private final DetectionDAO detectionDAO; - private StationDAO stationDAO; + private final StationDAO stationDAO; public StationDetectionManager(DetectionDAO detectionDAO, StationDAO stationDAO) { this.detectionDAO = detectionDAO; @@ -27,7 +27,7 @@ public Map timeSinceLastDetectionPerStation() { Optional maybeDetection = this.detectionDAO.latestDetectionByStationId(stationId); Optional maybeStation = this.stationDAO.getById(stationId); if (maybeDetection.isPresent() && maybeStation.isPresent()) { - Long time = maybeDetection.get().getTimestamp().getTime(); + long time = maybeDetection.get().getTimestamp().getTime(); stationIdToTimeSinceLatestDetection.put(maybeStation.get().getName(), (System.currentTimeMillis() - time) / 1000); } } diff --git a/src/main/java/telraam/monitoring/models/BatonDetection.java b/src/main/java/telraam/monitoring/models/BatonDetection.java index 646bf34..29eee97 100644 --- a/src/main/java/telraam/monitoring/models/BatonDetection.java +++ b/src/main/java/telraam/monitoring/models/BatonDetection.java @@ -1,7 +1,13 @@ package telraam.monitoring.models; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +@Setter +@Getter +@AllArgsConstructor public class BatonDetection { @JsonProperty("detected_time") private Integer detectionTime; @@ -13,52 +19,4 @@ public class BatonDetection { private Integer stationId; @JsonProperty("team_name") private String teamName; - - public BatonDetection(Integer detectionTime, Integer rssi, Integer stationId, Integer teamId, String teamName) { - this.detectionTime = detectionTime; - this.rssi = rssi; - this.stationId = stationId; - this.teamId = teamId; - this.teamName = teamName; - } - - public Integer getDetectionTime() { - return detectionTime; - } - - public void setDetectionTime(Integer detectionTime) { - this.detectionTime = detectionTime; - } - - public Integer getRssi() { - return rssi; - } - - public void setRssi(Integer rssi) { - this.rssi = rssi; - } - - public Integer getTeamId() { - return teamId; - } - - public void setTeamId(Integer teamId) { - this.teamId = teamId; - } - - public Integer getStationId() { - return stationId; - } - - public void setStationId(Integer stationId) { - this.stationId = stationId; - } - - public String getTeamName() { - return teamName; - } - - public void setTeamName(String teamName) { - this.teamName = teamName; - } } diff --git a/src/main/java/telraam/monitoring/models/BatonStatus.java b/src/main/java/telraam/monitoring/models/BatonStatus.java index 947bd60..c719098 100644 --- a/src/main/java/telraam/monitoring/models/BatonStatus.java +++ b/src/main/java/telraam/monitoring/models/BatonStatus.java @@ -2,16 +2,20 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; import java.sql.Timestamp; +@Getter +@Setter public class BatonStatus { + private String mac; private Integer id; private String name; private Float battery; - // Uptime in seconds - private Long uptime; + private Long uptime; // Uptime in seconds private Boolean rebooted; @JsonProperty("time_since_seen") private Long lastSeenSecondsAgo; @@ -20,7 +24,7 @@ public class BatonStatus { @JsonProperty("last_detected_at_station") private Integer lastDetectedAtStation; - public BatonStatus(String mac, Integer id, String name, float battery, long uptime, boolean rebooted, Timestamp lastSeen, Integer LDAS) { + public BatonStatus(String mac, Integer id, String name, float battery, long uptime, boolean rebooted, Timestamp lastSeen, Integer lastDetectedAtStation) { this.mac = mac; this.id = id; this.name = name; @@ -29,79 +33,6 @@ public BatonStatus(String mac, Integer id, String name, float battery, long upti this.rebooted = rebooted; this.lastSeen = lastSeen; this.lastSeenSecondsAgo = lastSeen != null ? (System.currentTimeMillis() - lastSeen.getTime()) / 1000 : null; - this.lastDetectedAtStation = LDAS; - } - - // Getters and setters - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Float getBattery() { - return battery; - } - - public void setBattery(Float battery) { - this.battery = battery; - } - - public Long getUptime() { - return uptime; - } - - public void setUptime(Long uptime) { - this.uptime = uptime; - } - - public Boolean getRebooted() { - return rebooted; - } - - public void setRebooted(Boolean rebooted) { - this.rebooted = rebooted; - } - - public Long getLastSeenSecondsAgo() { - return lastSeenSecondsAgo; - } - - public void setLastSeenSecondsAgo(Long lastSeenSecondsAgo) { - this.lastSeenSecondsAgo = lastSeenSecondsAgo; - } - - public Timestamp getLastSeen() { - return lastSeen; - } - - public void setLastSeen(Timestamp lastSeen) { - this.lastSeen = lastSeen; - } - - public Integer getLastDetectedAtStation() { - return lastDetectedAtStation; - } - - public void setLastDetectedAtStation(Integer lastDetectedAtStation) { this.lastDetectedAtStation = lastDetectedAtStation; } diff --git a/src/main/java/telraam/monitoring/models/LapCountForTeam.java b/src/main/java/telraam/monitoring/models/LapCountForTeam.java index f75d8d0..3e8335e 100644 --- a/src/main/java/telraam/monitoring/models/LapCountForTeam.java +++ b/src/main/java/telraam/monitoring/models/LapCountForTeam.java @@ -1,17 +1,16 @@ package telraam.monitoring.models; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import java.util.Map; +@AllArgsConstructor public class LapCountForTeam { + @JsonProperty("team_name") private String teamName; + @JsonProperty("lap_counts") private Map lapCounts; - - public LapCountForTeam(String teamName, Map lapCounts) { - this.teamName = teamName; - this.lapCounts = lapCounts; - } } diff --git a/src/main/java/telraam/monitoring/models/TeamLapInfo.java b/src/main/java/telraam/monitoring/models/TeamLapInfo.java index 3473bd1..b244c27 100644 --- a/src/main/java/telraam/monitoring/models/TeamLapInfo.java +++ b/src/main/java/telraam/monitoring/models/TeamLapInfo.java @@ -1,21 +1,20 @@ package telraam.monitoring.models; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +@AllArgsConstructor public class TeamLapInfo { + @JsonProperty("lap_time") private long lapTime; + @JsonProperty("timestamp") private long timestamp; + @JsonProperty("team_id") private int teamId; + @JsonProperty("team_name") private String teamName; - - public TeamLapInfo(long lapTime, long timestamp, int teamId, String teamName) { - this.lapTime = lapTime; - this.timestamp = timestamp; - this.teamId = teamId; - this.teamName = teamName; - } } diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index bb0ed5e..fbd51b4 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -54,9 +54,9 @@ public Fetcher(Jdbi database, Station station, Set lappers, Set registeredConnections = new HashSet<>(); + private final Set registeredConnections = new HashSet<>(); private final ObjectMapper mapper = new ObjectMapper(); public void registerConnection(WebSocketConnection conn) { From 779cb94238a250d015c82a1fbf5b70f6854e3f46 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 2 Apr 2024 15:24:48 +0200 Subject: [PATCH 45/90] Slapper --- src/main/java/telraam/App.java | 2 + .../telraam/logic/lapper/slapper/Slapper.java | 139 ++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 src/main/java/telraam/logic/lapper/slapper/Slapper.java diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 5b1644e..b94b2e8 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -22,6 +22,7 @@ import telraam.logic.lapper.Lapper; import telraam.logic.lapper.external.ExternalLapper; import telraam.logic.lapper.robust.RobustLapper; +import telraam.logic.lapper.slapper.Slapper; import telraam.logic.positioner.Positioner; import telraam.logic.positioner.simple.SimplePositioner; import telraam.station.Fetcher; @@ -130,6 +131,7 @@ public void run(AppConfiguration configuration, Environment environment) { lappers.add(new ExternalLapper(this.database)); lappers.add(new RobustLapper(this.database)); + lappers.add(new Slapper(this.database)); // Enable lapper APIs for (Lapper lapper : lappers) { diff --git a/src/main/java/telraam/logic/lapper/slapper/Slapper.java b/src/main/java/telraam/logic/lapper/slapper/Slapper.java new file mode 100644 index 0000000..41ed3fc --- /dev/null +++ b/src/main/java/telraam/logic/lapper/slapper/Slapper.java @@ -0,0 +1,139 @@ +package telraam.logic.lapper.slapper; + +import io.dropwizard.jersey.setup.JerseyEnvironment; +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.LapSourceDAO; +import telraam.database.models.Detection; +import telraam.database.models.LapSource; +import telraam.logic.lapper.Lapper; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +// Lapper that only uses a single sql query +public class Slapper implements Lapper { + private final String SOURCE_NAME = "slapper"; + private final int DEBOUNCE_TIMEOUT = 10; + private final ScheduledExecutorService scheduler; + private boolean debounceScheduled; + private final Logger logger; + private final Jdbi jdbi; + + public Slapper(Jdbi jdbi) { + this.jdbi = jdbi; + this.scheduler = Executors.newScheduledThreadPool(1); + this.logger = Logger.getLogger(Slapper.class.getName()); + this.debounceScheduled = false; + + // Get the lapSourceId, create the source if needed + LapSourceDAO lapSourceDAO = jdbi.onDemand(LapSourceDAO.class); + if (lapSourceDAO.getByName(SOURCE_NAME).isEmpty()) { + lapSourceDAO.insert(new LapSource(SOURCE_NAME)); + } + } + + @Override + public void handle(Detection msg) { + if (!this.debounceScheduled) { + this.debounceScheduled = true; + this.scheduler.schedule(() -> { + try { + this.calculateLaps(); + } catch (Exception e) { + logger.severe(e.getMessage()); + } + this.debounceScheduled = false; + }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); + } + } + + private void calculateLaps() { + logger.info("Slapper: Calculating laps..."); + this.jdbi.useHandle(handle -> handle.execute( + """ + WITH switchovers AS ( + SELECT teamid AS team_id, + newbatonid, + timestamp AS start_timestamp, + COALESCE( + LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), + timestamp + INTERVAL '6 MONTHS' + ) AS next_baton_switch + FROM batonswitchover + ), + team_detections AS ( + SELECT MIN(station_id) AS station_id, + MAX(rssi) as rssi, + date_trunc('second', timestamp) AS timestamp_seconds, + team_id + FROM detection d + LEFT JOIN switchovers s ON d.baton_id = s.newbatonid + AND d.timestamp BETWEEN s.start_timestamp AND s.next_baton_switch + WHERE station_id NOT BETWEEN 3 AND 5 + AND rssi > -85 + AND team_id IS NOT NULL + GROUP BY date_trunc('second', timestamp), team_id + ), + no_duplicates AS ( + SELECT team_id, + timestamp_seconds, + FIRST_VALUE(timestamp_seconds) OVER ( + PARTITION BY team_id + ORDER BY timestamp_seconds + ) AS first_timestamp_seconds + FROM ( + SELECT *, + LAG(station_id) OVER ( + PARTITION BY team_id + ORDER BY timestamp_seconds + ) AS prev_station_id + FROM team_detections + ) AS previous + WHERE station_id - prev_station_id <= -5 + ), + new_laps AS ( + SELECT team_id, + timestamp_seconds + FROM no_duplicates n_d + WHERE timestamp_seconds > first_timestamp_seconds + ), + cst_source_id AS ( + SELECT COALESCE(id, -1) AS source_id + FROM lap_source + WHERE name ILIKE 'slapper' + ), + deletions AS ( + DELETE FROM lap l + WHERE lap_source_id = (SELECT source_id FROM cst_source_id) + AND NOT EXISTS ( + SELECT 1 + FROM new_laps n_l + WHERE l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds + ) + ) + INSERT INTO lap (team_id, timestamp, lap_source_id) + SELECT team_id, + timestamp_seconds, + source_id + FROM new_laps n_l, cst_source_id + WHERE NOT EXISTS ( + SELECT 1 + FROM lap l, cst_source_id + WHERE l.lap_source_id = source_id + AND l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds + ) + """ + ) + ); + logger.info("Slapper: Done calculating laps"); + } + + @Override + public void registerAPI(JerseyEnvironment jersey) { + + } +} From 521dc8f9a3e5f1bb28b28c317aa38abf3b714350 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Thu, 4 Apr 2024 11:41:29 +0200 Subject: [PATCH 46/90] slapper query change --- .../telraam/logic/lapper/slapper/Slapper.java | 114 +++++++++--------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/src/main/java/telraam/logic/lapper/slapper/Slapper.java b/src/main/java/telraam/logic/lapper/slapper/Slapper.java index 41ed3fc..17b7f9f 100644 --- a/src/main/java/telraam/logic/lapper/slapper/Slapper.java +++ b/src/main/java/telraam/logic/lapper/slapper/Slapper.java @@ -54,77 +54,77 @@ private void calculateLaps() { this.jdbi.useHandle(handle -> handle.execute( """ WITH switchovers AS ( - SELECT teamid AS team_id, - newbatonid, - timestamp AS start_timestamp, - COALESCE( - LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), - timestamp + INTERVAL '6 MONTHS' - ) AS next_baton_switch - FROM batonswitchover + SELECT teamid AS team_id, + newbatonid, + timestamp AS start_timestamp, + COALESCE( + LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), + timestamp + INTERVAL '1 MONTH' + ) AS next_baton_switch + FROM batonswitchover ), team_detections AS ( - SELECT MIN(station_id) AS station_id, - MAX(rssi) as rssi, - date_trunc('second', timestamp) AS timestamp_seconds, - team_id - FROM detection d - LEFT JOIN switchovers s ON d.baton_id = s.newbatonid - AND d.timestamp BETWEEN s.start_timestamp AND s.next_baton_switch - WHERE station_id NOT BETWEEN 3 AND 5 - AND rssi > -85 - AND team_id IS NOT NULL - GROUP BY date_trunc('second', timestamp), team_id + SELECT MIN(station_id) AS station_id, + MAX(rssi) as rssi, + date_trunc('second', timestamp) AS timestamp_seconds, + team_id + FROM detection d + LEFT JOIN switchovers s ON d.baton_id = s.newbatonid + AND d.timestamp BETWEEN s.start_timestamp AND s.next_baton_switch + WHERE station_id NOT BETWEEN 3 AND 5 + AND rssi > -84 + AND team_id IS NOT NULL + GROUP BY date_trunc('second', timestamp), team_id ), - no_duplicates AS ( - SELECT team_id, - timestamp_seconds, - FIRST_VALUE(timestamp_seconds) OVER ( - PARTITION BY team_id - ORDER BY timestamp_seconds - ) AS first_timestamp_seconds - FROM ( - SELECT *, - LAG(station_id) OVER ( - PARTITION BY team_id - ORDER BY timestamp_seconds - ) AS prev_station_id - FROM team_detections - ) AS previous - WHERE station_id - prev_station_id <= -5 + start_times AS ( + SELECT DISTINCT ON (team_id) team_id, + timestamp_seconds AS start_seconds + FROM team_detections + WHERE station_id BETWEEN 2 AND 3 + ORDER BY team_id, timestamp_seconds ), new_laps AS ( - SELECT team_id, - timestamp_seconds - FROM no_duplicates n_d - WHERE timestamp_seconds > first_timestamp_seconds + SELECT previous.team_id, + timestamp_seconds + FROM ( + SELECT *, + LAG(station_id) OVER ( + PARTITION BY team_id + ORDER BY timestamp_seconds + ) AS prev_station_id + FROM team_detections + ) AS previous + LEFT JOIN start_times s_t + ON previous.team_id = s_t.team_id + WHERE station_id - prev_station_id < -4 + AND timestamp_seconds > start_seconds ), cst_source_id AS ( - SELECT COALESCE(id, -1) AS source_id - FROM lap_source - WHERE name ILIKE 'slapper' + SELECT COALESCE(id, -1) AS source_id + FROM lap_source + WHERE name ILIKE 'slapper' ), deletions AS ( - DELETE FROM lap l - WHERE lap_source_id = (SELECT source_id FROM cst_source_id) - AND NOT EXISTS ( - SELECT 1 - FROM new_laps n_l - WHERE l.team_id = n_l.team_id - AND l.timestamp = n_l.timestamp_seconds - ) + DELETE FROM lap l + WHERE lap_source_id = (SELECT source_id FROM cst_source_id) + AND NOT EXISTS ( + SELECT 1 + FROM new_laps n_l + WHERE l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds + ) ) INSERT INTO lap (team_id, timestamp, lap_source_id) SELECT team_id, - timestamp_seconds, - source_id + timestamp_seconds, + source_id FROM new_laps n_l, cst_source_id WHERE NOT EXISTS ( - SELECT 1 - FROM lap l, cst_source_id - WHERE l.lap_source_id = source_id - AND l.team_id = n_l.team_id - AND l.timestamp = n_l.timestamp_seconds + SELECT 1 + FROM lap l, cst_source_id + WHERE l.lap_source_id = source_id + AND l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds ) """ ) From 2306e50cfe8a81c488909853fe64311964fc4519 Mon Sep 17 00:00:00 2001 From: Jan Lecoutere Date: Thu, 4 Apr 2024 23:36:30 +0200 Subject: [PATCH 47/90] feat(teams): add jacketNr to team model (#132) * feat(teams): add jacketNr to team model * refactor(teams): use string for jacketNr * fix: update default value --- src/main/java/telraam/database/daos/TeamDAO.java | 7 ++----- src/main/java/telraam/database/models/Team.java | 1 + .../resources/db/migration/V16__Add_team_jacket_nr.sql | 1 + src/test/java/telraam/database/daos/TeamDAOTest.java | 2 ++ 4 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 src/main/resources/db/migration/V16__Add_team_jacket_nr.sql diff --git a/src/main/java/telraam/database/daos/TeamDAO.java b/src/main/java/telraam/database/daos/TeamDAO.java index e983c57..77d8c84 100644 --- a/src/main/java/telraam/database/daos/TeamDAO.java +++ b/src/main/java/telraam/database/daos/TeamDAO.java @@ -19,7 +19,7 @@ public interface TeamDAO extends DAO { List getAll(); @Override - @SqlUpdate("INSERT INTO team (name, baton_id) VALUES (:name, :batonId)") + @SqlUpdate("INSERT INTO team (name, baton_id, jacket_nr) VALUES (:name, :batonId, :jacketNr)") @GetGeneratedKeys({"id"}) int insert(@BindBean Team team); @@ -33,9 +33,6 @@ public interface TeamDAO extends DAO { int deleteById(@Bind("id") int id); @Override - @SqlUpdate("UPDATE team SET " + - "name = :name," + - "baton_id = :batonId " + - "WHERE id = :id") + @SqlUpdate("UPDATE team SET name = :name, baton_id = :batonId, jacket_nr = :jacketNr WHERE id = :id") int update(@Bind("id") int id, @BindBean Team modelObj); } diff --git a/src/main/java/telraam/database/models/Team.java b/src/main/java/telraam/database/models/Team.java index 94db208..eb5e086 100644 --- a/src/main/java/telraam/database/models/Team.java +++ b/src/main/java/telraam/database/models/Team.java @@ -9,6 +9,7 @@ public class Team { private Integer id; private String name; private Integer batonId; + private String jacketNr = "INVALID"; public Team(String name) { this.name = name; diff --git a/src/main/resources/db/migration/V16__Add_team_jacket_nr.sql b/src/main/resources/db/migration/V16__Add_team_jacket_nr.sql new file mode 100644 index 0000000..9b261db --- /dev/null +++ b/src/main/resources/db/migration/V16__Add_team_jacket_nr.sql @@ -0,0 +1 @@ +alter table team add jacket_nr varchar(255) default 'INVALID' not null; \ No newline at end of file diff --git a/src/test/java/telraam/database/daos/TeamDAOTest.java b/src/test/java/telraam/database/daos/TeamDAOTest.java index 775efa9..7dae6b7 100644 --- a/src/test/java/telraam/database/daos/TeamDAOTest.java +++ b/src/test/java/telraam/database/daos/TeamDAOTest.java @@ -103,12 +103,14 @@ void testUpdateDoesUpdate() { int testid = teamDAO.insert(testTeam); testTeam.setId(testid); testTeam.setName("postupdate"); + testTeam.setJacketNr("10"); int updatedRows = teamDAO.update(testid, testTeam); assertEquals(1, updatedRows); Optional dbTeam = teamDAO.getById(testid); assertFalse(dbTeam.isEmpty()); assertEquals("postupdate", dbTeam.get().getName()); + assertEquals("10", dbTeam.get().getJacketNr()); } @Test From ae537f80530c923f8e6932e996e4ff64e6b1172e Mon Sep 17 00:00:00 2001 From: Topvennie Date: Mon, 8 Apr 2024 17:59:21 +0200 Subject: [PATCH 48/90] remove min station --- .../telraam/logic/lapper/slapper/Slapper.java | 144 +++++++++--------- 1 file changed, 72 insertions(+), 72 deletions(-) diff --git a/src/main/java/telraam/logic/lapper/slapper/Slapper.java b/src/main/java/telraam/logic/lapper/slapper/Slapper.java index 17b7f9f..e4a34af 100644 --- a/src/main/java/telraam/logic/lapper/slapper/Slapper.java +++ b/src/main/java/telraam/logic/lapper/slapper/Slapper.java @@ -54,78 +54,78 @@ private void calculateLaps() { this.jdbi.useHandle(handle -> handle.execute( """ WITH switchovers AS ( - SELECT teamid AS team_id, - newbatonid, - timestamp AS start_timestamp, - COALESCE( - LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), - timestamp + INTERVAL '1 MONTH' - ) AS next_baton_switch - FROM batonswitchover - ), - team_detections AS ( - SELECT MIN(station_id) AS station_id, - MAX(rssi) as rssi, - date_trunc('second', timestamp) AS timestamp_seconds, - team_id - FROM detection d - LEFT JOIN switchovers s ON d.baton_id = s.newbatonid - AND d.timestamp BETWEEN s.start_timestamp AND s.next_baton_switch - WHERE station_id NOT BETWEEN 3 AND 5 - AND rssi > -84 - AND team_id IS NOT NULL - GROUP BY date_trunc('second', timestamp), team_id - ), - start_times AS ( - SELECT DISTINCT ON (team_id) team_id, - timestamp_seconds AS start_seconds - FROM team_detections - WHERE station_id BETWEEN 2 AND 3 - ORDER BY team_id, timestamp_seconds - ), - new_laps AS ( - SELECT previous.team_id, - timestamp_seconds - FROM ( - SELECT *, - LAG(station_id) OVER ( - PARTITION BY team_id - ORDER BY timestamp_seconds - ) AS prev_station_id - FROM team_detections - ) AS previous - LEFT JOIN start_times s_t - ON previous.team_id = s_t.team_id - WHERE station_id - prev_station_id < -4 - AND timestamp_seconds > start_seconds - ), - cst_source_id AS ( - SELECT COALESCE(id, -1) AS source_id - FROM lap_source - WHERE name ILIKE 'slapper' - ), - deletions AS ( - DELETE FROM lap l - WHERE lap_source_id = (SELECT source_id FROM cst_source_id) - AND NOT EXISTS ( - SELECT 1 - FROM new_laps n_l - WHERE l.team_id = n_l.team_id - AND l.timestamp = n_l.timestamp_seconds - ) - ) - INSERT INTO lap (team_id, timestamp, lap_source_id) - SELECT team_id, - timestamp_seconds, - source_id - FROM new_laps n_l, cst_source_id - WHERE NOT EXISTS ( - SELECT 1 - FROM lap l, cst_source_id - WHERE l.lap_source_id = source_id - AND l.team_id = n_l.team_id - AND l.timestamp = n_l.timestamp_seconds - ) + SELECT teamid AS team_id, + newbatonid, + timestamp AS start_timestamp, + COALESCE( + LEAD(timestamp) OVER (PARTITION BY teamid ORDER BY timestamp), + timestamp + INTERVAL '1 MONTH' + ) AS next_baton_switch + FROM batonswitchover + ), + team_detections AS ( + SELECT station_id, + MAX(rssi) as rssi, + date_trunc('second', timestamp) AS timestamp_seconds, + team_id + FROM detection d + LEFT JOIN switchovers s ON d.baton_id = s.newbatonid + AND d.timestamp BETWEEN s.start_timestamp AND s.next_baton_switch + WHERE station_id NOT BETWEEN 3 AND 5 + AND rssi > -84 + AND team_id IS NOT NULL + GROUP BY date_trunc('second', timestamp), team_id, station_id + ), + start_times AS ( + SELECT DISTINCT ON (team_id) team_id, + timestamp_seconds AS start_seconds + FROM team_detections + WHERE station_id BETWEEN 2 AND 3 + ORDER BY team_id, timestamp_seconds + ), + new_laps AS ( + SELECT previous.team_id, + timestamp_seconds + FROM ( + SELECT *, + LAG(station_id) OVER ( + PARTITION BY team_id + ORDER BY timestamp_seconds + ) AS prev_station_id + FROM team_detections + ) AS previous + LEFT JOIN start_times s_t + ON previous.team_id = s_t.team_id + WHERE station_id - prev_station_id < -4 + AND timestamp_seconds > start_seconds + ), + cst_source_id AS ( + SELECT COALESCE(id, -1) AS source_id + FROM lap_source + WHERE name ILIKE 'slapper' + ), + deletions AS ( + DELETE FROM lap l + WHERE lap_source_id = (SELECT source_id FROM cst_source_id) + AND NOT EXISTS ( + SELECT 1 + FROM new_laps n_l + WHERE l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds + ) + ) + INSERT INTO lap (team_id, timestamp, lap_source_id) + SELECT team_id, + timestamp_seconds, + source_id + FROM new_laps n_l, cst_source_id + WHERE NOT EXISTS ( + SELECT 1 + FROM lap l, cst_source_id + WHERE l.lap_source_id = source_id + AND l.team_id = n_l.team_id + AND l.timestamp = n_l.timestamp_seconds + ) """ ) ); From 29daae2978e1599d2bdfb8e9f45f78e497fdd6f5 Mon Sep 17 00:00:00 2001 From: Jan Lecoutere Date: Sun, 14 Apr 2024 16:52:44 +0200 Subject: [PATCH 49/90] feat(lapCountResource): add lap count per source & team (#131) * feat(lapCountResource): add lap count per source & team End date should be the date of the postgres DB so in our normal settingg, the local time (UTC + 2) * feat(LapCount): add endpoint for count for all teams for specific lapSource * refactor(LapDao): unify getAllBeforeTime query results * fix(LapCountResource): make DAO attributes private --- src/main/java/telraam/App.java | 2 +- .../java/telraam/api/LapCountResource.java | 34 +++++++++++++++++-- .../java/telraam/database/daos/LapDAO.java | 9 +++++ .../telraam/database/models/LapCount.java | 11 ++++++ 4 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/main/java/telraam/database/models/LapCount.java diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index b94b2e8..4075bbd 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -110,7 +110,7 @@ public void run(AppConfiguration configuration, Environment environment) { jersey.register(new LapSourceSwitchoverResource(database.onDemand(LapSourceSwitchoverDAO.class))); jersey.register(new AcceptedLapsResource()); jersey.register(new TimeResource()); - jersey.register(new LapCountResource(database.onDemand(TeamDAO.class))); + jersey.register(new LapCountResource(database.onDemand(TeamDAO.class), database.onDemand(LapDAO.class))); jersey.register(new MonitoringResource(database)); environment.healthChecks().register("template", new TemplateHealthCheck(configuration.getTemplate())); diff --git a/src/main/java/telraam/api/LapCountResource.java b/src/main/java/telraam/api/LapCountResource.java index b8ca04d..edb7b03 100644 --- a/src/main/java/telraam/api/LapCountResource.java +++ b/src/main/java/telraam/api/LapCountResource.java @@ -1,15 +1,20 @@ package telraam.api; +import telraam.database.daos.LapDAO; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import telraam.database.daos.TeamDAO; import telraam.database.models.Lap; +import telraam.database.models.LapCount; import telraam.database.models.Team; import telraam.util.AcceptedLapsUtil; +import java.sql.Timestamp; +import java.time.LocalDateTime; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -17,10 +22,12 @@ @Tag(name="Lap Counts") @Produces(MediaType.APPLICATION_JSON) public class LapCountResource { - TeamDAO teamDAO; + private TeamDAO teamDAO; + private LapDAO lapDAO; - public LapCountResource(TeamDAO teamDAO) { + public LapCountResource(TeamDAO teamDAO, LapDAO lapDAO) { this.teamDAO = teamDAO; + this.lapDAO = lapDAO; } @GET @@ -53,4 +60,27 @@ public Map getLapCounts() { return perName; } + + @GET + @Path("/{lapSourceId}") + public List getLapCountForLapSource(@PathParam("lapSourceId") Integer id, @QueryParam("end") Optional endTimestamp) { + LocalDateTime dateTime = LocalDateTime.now(); + if (endTimestamp.isPresent()) { + dateTime = LocalDateTime.parse(endTimestamp.get()); + } + List laps = lapDAO.getAllBeforeTime(id, Timestamp.valueOf(dateTime)); + return laps; + } + + // EndTimestamp should be a ISO formatted date timestamp + @GET + @Path("/{lapSourceId}/{teamId}") + public Integer getLapCountForLapSource(@PathParam("lapSourceId") Integer id, @PathParam("teamId") Integer teamId, @QueryParam("end") Optional endTimestamp) { + LocalDateTime dateTime = LocalDateTime.now(); + if (endTimestamp.isPresent()) { + dateTime = LocalDateTime.parse(endTimestamp.get()); + } + LapCount lapInfo = lapDAO.getAllForTeamBeforeTime(id, teamId, Timestamp.valueOf(dateTime)); + return lapInfo.getCount(); + } } diff --git a/src/main/java/telraam/database/daos/LapDAO.java b/src/main/java/telraam/database/daos/LapDAO.java index f484f6f..8afd163 100644 --- a/src/main/java/telraam/database/daos/LapDAO.java +++ b/src/main/java/telraam/database/daos/LapDAO.java @@ -8,6 +8,7 @@ import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import telraam.database.models.Lap; +import telraam.database.models.LapCount; import telraam.database.models.TeamLapCount; import java.sql.Timestamp; @@ -29,6 +30,14 @@ public interface LapDAO extends DAO { @RegisterBeanMapper(Lap.class) List getAllBySourceSorted(@Bind("lapSourceId") Integer lapSourceId); + @SqlQuery("SELECT t.id as team_id, (SELECT COUNT(*) FROM lap WHERE lap_source_id = :lapSourceId AND timestamp <= :timestamp and team_id = t.id) as count FROM team t") + @RegisterBeanMapper(LapCount.class) + List getAllBeforeTime(@Bind("lapSourceId") Integer lapSourceId, @Bind("timestamp") Timestamp timestamp); + + @SqlQuery("SELECT t.id as team_id, (SELECT COUNT(*) FROM lap WHERE lap_source_id = :lapSourceId AND timestamp <= :timestamp and team_id = t.id) as count FROM team t where id = :teamId") + @RegisterBeanMapper(LapCount.class) + LapCount getAllForTeamBeforeTime(@Bind("lapSourceId") Integer lapSourceId, @Bind("teamId") Integer teamId, @Bind("timestamp") Timestamp timestamp); + @SqlUpdate("INSERT INTO lap (team_id, lap_source_id, timestamp) " + "VALUES (:teamId, :lapSourceId, :timestamp)") @GetGeneratedKeys({"id"}) diff --git a/src/main/java/telraam/database/models/LapCount.java b/src/main/java/telraam/database/models/LapCount.java new file mode 100644 index 0000000..a3831a5 --- /dev/null +++ b/src/main/java/telraam/database/models/LapCount.java @@ -0,0 +1,11 @@ +package telraam.database.models; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter @Setter @NoArgsConstructor +public class LapCount { + private int teamId; + private int count; +} From dfd4510f4ba7796b840063dd49e4a996393934d5 Mon Sep 17 00:00:00 2001 From: Jan Lecoutere Date: Mon, 22 Apr 2024 19:35:18 +0200 Subject: [PATCH 50/90] feat: add WS station fetcher (#135) * refactor(station): replace timed http request with websockets * feat(station): send InitMessage on open connection * refactor: Use jakarta websockets * feat: re-add http fetcher & move WS to own package * fix(ws-fetcher): catch client creation error * feat(ws-fetcher): open WS after setting handlers * feat(ws-fetcher): retrieve missing values for detections from DB & try to fix simplePositioner cursedness with threading * fix(simplePositioner): make handle function synchronised * fix(gradle): replace impl with jersey one is more in line with what we use for our server impl * fix(ws-fetcher): use lombok annotation * fix(ws-fetcher): baton mac's to uppercase * ingrease message size --------- Co-authored-by: FKD13 <44001949+FKD13@users.noreply.github.com> --- build.gradle | 6 + src/main/java/telraam/App.java | 6 +- .../telraam/database/daos/DetectionDAO.java | 8 + .../telraam/database/models/Detection.java | 4 +- .../java/telraam/database/models/Team.java | 10 +- .../positioner/simple/SimplePositioner.java | 35 ++-- src/main/java/telraam/station/Fetcher.java | 182 +----------------- .../java/telraam/station/FetcherFactory.java | 42 ++++ .../telraam/station/http/HTTPFetcher.java | 174 +++++++++++++++++ .../station/{ => http}/JsonBodyHandler.java | 15 +- .../telraam/station/models/RonnyResponse.java | 2 +- .../station/websocket/WebsocketClient.java | 75 ++++++++ .../station/websocket/WebsocketFetcher.java | 165 ++++++++++++++++ 13 files changed, 518 insertions(+), 206 deletions(-) create mode 100644 src/main/java/telraam/station/FetcherFactory.java create mode 100644 src/main/java/telraam/station/http/HTTPFetcher.java rename src/main/java/telraam/station/{ => http}/JsonBodyHandler.java (97%) create mode 100644 src/main/java/telraam/station/websocket/WebsocketClient.java create mode 100644 src/main/java/telraam/station/websocket/WebsocketFetcher.java diff --git a/build.gradle b/build.gradle index 6800130..6dd0107 100644 --- a/build.gradle +++ b/build.gradle @@ -66,6 +66,12 @@ dependencies { 'org.eclipse.jetty.websocket:websocket-jetty-api:' + jettyVersion, 'org.eclipse.jetty.websocket:websocket-jetty-server:' + jettyVersion, ) + + // Websocket client libs + compileOnly 'jakarta.websocket:jakarta.websocket-client-api:2.2.0-M1' + // Impl for jakarta websocket clients + implementation 'org.eclipse.jetty.websocket:websocket-jakarta-client:11.0.20' + // Database implementation('com.h2database:h2:2.2.220') implementation('org.postgresql:postgresql:42.7.3') diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 4075bbd..08a3847 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -25,7 +25,8 @@ import telraam.logic.lapper.slapper.Slapper; import telraam.logic.positioner.Positioner; import telraam.logic.positioner.simple.SimplePositioner; -import telraam.station.Fetcher; +import telraam.station.FetcherFactory; +import telraam.station.websocket.WebsocketFetcher; import telraam.util.AcceptedLapsUtil; import telraam.websocket.WebSocketConnection; @@ -144,9 +145,10 @@ public void run(AppConfiguration configuration, Environment environment) { positioners.add(new SimplePositioner(this.database)); // Start fetch thread for each station + FetcherFactory fetcherFactory = new FetcherFactory(this.database, lappers, positioners); StationDAO stationDAO = this.database.onDemand(StationDAO.class); for (Station station : stationDAO.getAll()) { - new Thread(() -> new Fetcher(this.database, station, lappers, positioners).fetch()).start(); + new Thread(() -> fetcherFactory.create(station).fetch()).start(); } } diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index c50452e..4e45e3c 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -33,6 +33,14 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id @GetGeneratedKeys({"id"}) int insertAll(@BindBean List detection); + @SqlBatch(""" + INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id, uptime_ms, timestamp_ingestion) \ + VALUES (:stationId, (SELECT id FROM baton WHERE mac = :batonMac), :timestamp, :rssi, :battery, :remoteId, :uptimeMs, :timestampIngestion) + """) + @GetGeneratedKeys({"id", "baton_id"}) + @RegisterBeanMapper(Detection.class) + List insertAllWithoutBaton(@BindBean List detection, @Bind("batonMac") List batonMac); + @SqlQuery("SELECT * FROM detection WHERE id = :id") @RegisterBeanMapper(Detection.class) Optional getById(@Bind("id") int id); diff --git a/src/main/java/telraam/database/models/Detection.java b/src/main/java/telraam/database/models/Detection.java index 23a4067..5cd050b 100644 --- a/src/main/java/telraam/database/models/Detection.java +++ b/src/main/java/telraam/database/models/Detection.java @@ -6,7 +6,9 @@ import java.sql.Timestamp; -@Setter @Getter @NoArgsConstructor +@Setter +@Getter +@NoArgsConstructor public class Detection { private Integer id; private Integer batonId; diff --git a/src/main/java/telraam/database/models/Team.java b/src/main/java/telraam/database/models/Team.java index eb5e086..317b2ed 100644 --- a/src/main/java/telraam/database/models/Team.java +++ b/src/main/java/telraam/database/models/Team.java @@ -4,7 +4,11 @@ import lombok.NoArgsConstructor; import lombok.Setter; -@Getter @Setter @NoArgsConstructor +import java.util.Objects; + +@Getter +@Setter +@NoArgsConstructor public class Team { private Integer id; private String name; @@ -19,4 +23,8 @@ public Team(String name, int batonId) { this.name = name; this.batonId = batonId; } + + public boolean equals(Team obj) { + return Objects.equals(id, obj.getId()); + } } diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java index f8a9022..9958d1e 100644 --- a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java +++ b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java @@ -13,27 +13,27 @@ import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; import java.util.logging.Logger; public class SimplePositioner implements Positioner { + private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); private final int QUEUE_SIZE = 50; private final int MIN_RSSI = -85; private final int DEBOUNCE_TIMEOUT = 1; private boolean debounceScheduled; private final ScheduledExecutorService scheduler; - private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); private final PositionSender positionSender; private final Map batonIdToTeam; - private final Map> teamDetections; + private final Map> teamDetections; private final List stations; - private final Map teamPositions; + private final Map teamPositions; public SimplePositioner(Jdbi jdbi) { this.debounceScheduled = false; @@ -45,14 +45,14 @@ public SimplePositioner(Jdbi jdbi) { TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); List teams = teamDAO.getAll(); - for (Team team: teams) { - teamDetections.put(team, new CircularQueue<>(QUEUE_SIZE)); - teamPositions.put(team, new Position(team.getId())); + for (Team team : teams) { + teamDetections.put(team.getId(), new CircularQueue<>(QUEUE_SIZE)); + teamPositions.put(team.getId(), new Position(team.getId())); } List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); - for (BatonSwitchover switchover: switchovers) { + for (BatonSwitchover switchover : switchovers) { batonIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); } @@ -63,13 +63,13 @@ public SimplePositioner(Jdbi jdbi) { public void calculatePositions() { logger.info("SimplePositioner: Calculating positions..."); - for (Map.Entry> entry: teamDetections.entrySet()) { + for (Map.Entry> entry : teamDetections.entrySet()) { List detections = teamDetections.get(entry.getKey()); detections.sort(Comparator.comparing(Detection::getTimestamp)); int currentStationRssi = MIN_RSSI; int currentStationPosition = 0; - for (Detection detection: detections) { + for (Detection detection : detections) { if (detection.getRssi() > currentStationRssi) { currentStationRssi = detection.getRssi(); currentStationPosition = detection.getStationId(); @@ -84,21 +84,20 @@ public void calculatePositions() { logger.info("SimplePositioner: Done calculating positions"); } - public void handle(Detection detection) { + public synchronized void handle(Detection detection) { Team team = batonIdToTeam.get(detection.getBatonId()); - teamDetections.get(team).add(detection); + teamDetections.get(team.getId()).add(detection); - if (! debounceScheduled) { + if (!debounceScheduled) { debounceScheduled = true; scheduler.schedule(() -> { try { calculatePositions(); } catch (Exception e) { - logger.severe(e.getMessage()); + logger.log(Level.SEVERE, e.getMessage(), e); } debounceScheduled = false; }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); } } - } diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index fbd51b4..753474a 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -1,182 +1,14 @@ package telraam.station; -import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonDAO; -import telraam.database.daos.DetectionDAO; -import telraam.database.daos.StationDAO; -import telraam.database.models.Baton; -import telraam.database.models.Detection; -import telraam.database.models.Station; -import telraam.logic.lapper.Lapper; -import telraam.logic.positioner.Positioner; -import telraam.station.models.RonnyDetection; -import telraam.station.models.RonnyResponse; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.http.HttpClient; -import java.net.http.HttpConnectTimeoutException; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.sql.Timestamp; -import java.time.Duration; -import java.util.*; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -public class Fetcher { - private final Set lappers; - private final Set positioners; - private Station station; - - private final BatonDAO batonDAO; - private final DetectionDAO detectionDAO; - private final StationDAO stationDAO; - - private final HttpClient client = HttpClient.newHttpClient(); - private final Logger logger = Logger.getLogger(Fetcher.class.getName()); - +public interface Fetcher { //Timeout to wait for before sending the next request after an error. - private final static int ERROR_TIMEOUT_MS = 2000; + int ERROR_TIMEOUT_MS = 2000; //Timeout for a request to a station. - private final static int REQUEST_TIMEOUT_S = 10; + int REQUEST_TIMEOUT_S = 10; //Full batch size, if this number of detections is reached, more are probably available immediately. - private final static int FULL_BATCH_SIZE = 1000; + int FULL_BATCH_SIZE = 1000; //Timeout when result has less than a full batch of detections. - private final static int IDLE_TIMEOUT_MS = 4000; // Wait 4 seconds - - - public Fetcher(Jdbi database, Station station, Set lappers, Set positioners) { - this.batonDAO = database.onDemand(BatonDAO.class); - this.detectionDAO = database.onDemand(DetectionDAO.class); - this.stationDAO = database.onDemand(StationDAO.class); - - this.lappers = lappers; - this.positioners = positioners; - this.station = station; - } - - public void fetch() { - logger.info("Running Fetcher for station(" + this.station.getId() + ")"); - JsonBodyHandler bodyHandler = new JsonBodyHandler<>(RonnyResponse.class); - - while (true) { - //Update the station to account for possible changes in the database - this.stationDAO.getById(station.getId()).ifPresentOrElse( - station -> this.station = station, - () -> this.logger.severe("Can't update station from database.") - ); - - //Get last detection id - int lastDetectionId = 0; - Optional lastDetection = detectionDAO.latestDetectionByStationId(this.station.getId()); - if (lastDetection.isPresent()) { - lastDetectionId = lastDetection.get().getRemoteId(); - } - - //Create URL - URI url; - try { - url = new URI(station.getUrl() + "/detections/" + lastDetectionId); - } catch (URISyntaxException ex) { - this.logger.severe(ex.getMessage()); - try { - Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); - } catch (InterruptedException e) { - logger.severe(e.getMessage()); - } - continue; - } - - //Create request - HttpRequest request; - try { - request = HttpRequest.newBuilder() - .uri(url) - .version(HttpClient.Version.HTTP_1_1) - .timeout(Duration.ofSeconds(Fetcher.REQUEST_TIMEOUT_S)) - .build(); - } catch (IllegalArgumentException e) { - logger.severe(e.getMessage()); - try { - Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); - } catch (InterruptedException ex) { - logger.severe(ex.getMessage()); - } - continue; - } - - //Do request - HttpResponse> response; - try { - try { - response = this.client.send(request, bodyHandler); - } catch (ConnectException | HttpConnectTimeoutException ex) { - this.logger.severe("Could not connect to " + request.uri()); - Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); - continue; - } catch (IOException e) { - logger.severe(e.getMessage()); - Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); - continue; - } - } catch (InterruptedException e) { - logger.severe(e.getMessage()); - continue; - } - - //Check response state - if (response.statusCode() != 200) { - this.logger.warning( - "Unexpected status code(" + response.statusCode() + ") when requesting " + url + " for station(" + this.station.getName() + ")" - ); - continue; - } - - //Fetch all batons and create a map by batonMAC - Map baton_mac_map = batonDAO.getAll().stream() - .collect(Collectors.toMap(b -> b.getMac().toUpperCase(), Function.identity())); - - //Insert detections - List new_detections = new ArrayList<>(); - List detections = response.body().get().detections; - for (RonnyDetection detection : detections) { - if (baton_mac_map.containsKey(detection.mac.toUpperCase())) { - var baton = baton_mac_map.get(detection.mac.toUpperCase()); - new_detections.add(new Detection( - baton.getId(), - station.getId(), - detection.rssi, - detection.battery, - detection.uptimeMs, - detection.id, - new Timestamp((long) (detection.detectionTimestamp * 1000)), - new Timestamp(System.currentTimeMillis()) - )); - } - } - if (!new_detections.isEmpty()) { - detectionDAO.insertAll(new_detections); - new_detections.forEach((detection) -> { - lappers.forEach((lapper) -> lapper.handle(detection)); - positioners.forEach((positioner) -> positioner.handle(detection)); - }); - } - - this.logger.finer("Fetched " + detections.size() + " detections from " + station.getName() + ", Saved " + new_detections.size()); + int IDLE_TIMEOUT_MS = 4000; // Wait 4 seconds - //If few detections are retrieved from the station, wait for some time. - if (detections.size() < Fetcher.FULL_BATCH_SIZE) { - try { - Thread.sleep(Fetcher.IDLE_TIMEOUT_MS); - } catch (InterruptedException e) { - logger.severe(e.getMessage()); - } - } - } - } -} \ No newline at end of file + void fetch(); +} diff --git a/src/main/java/telraam/station/FetcherFactory.java b/src/main/java/telraam/station/FetcherFactory.java new file mode 100644 index 0000000..b3cb487 --- /dev/null +++ b/src/main/java/telraam/station/FetcherFactory.java @@ -0,0 +1,42 @@ +package telraam.station; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.models.Station; +import telraam.logic.lapper.Lapper; +import telraam.logic.positioner.Positioner; +import telraam.station.http.HTTPFetcher; +import telraam.station.websocket.WebsocketFetcher; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Set; +import java.util.logging.Logger; + +public class FetcherFactory { + private final Logger logger = Logger.getLogger(FetcherFactory.class.getName()); + private final Jdbi database; + private final Set lappers; + private final Set positioners; + public FetcherFactory(Jdbi database, Set lappers, Set positioners) { + this.database = database; + this.lappers = lappers; + this.positioners = positioners; + } + + public Fetcher create(Station station) { + try { + URI stationURI = new URI(station.getUrl()); + return switch (stationURI.getScheme()) { + case "ws" -> new WebsocketFetcher(database, station, lappers, positioners); + case "http" -> new HTTPFetcher(database, station, lappers, positioners); + default -> { + logger.severe(String.format("%s is not a valid scheme for a station", stationURI.getScheme())); + yield null; + } + }; + } catch (URISyntaxException e) { + logger.severe(String.format("Failed to parse station URI: %s", e.getMessage())); + } + return null; + } +} diff --git a/src/main/java/telraam/station/http/HTTPFetcher.java b/src/main/java/telraam/station/http/HTTPFetcher.java new file mode 100644 index 0000000..c296efd --- /dev/null +++ b/src/main/java/telraam/station/http/HTTPFetcher.java @@ -0,0 +1,174 @@ +package telraam.station.http; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonDAO; +import telraam.database.daos.DetectionDAO; +import telraam.database.daos.StationDAO; +import telraam.database.models.Baton; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.logic.lapper.Lapper; +import telraam.logic.positioner.Positioner; +import telraam.station.Fetcher; +import telraam.station.models.RonnyDetection; +import telraam.station.models.RonnyResponse; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Timestamp; +import java.time.Duration; +import java.util.*; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class HTTPFetcher implements Fetcher { + private final Set lappers; + private final Set positioners; + private Station station; + + private final BatonDAO batonDAO; + private final DetectionDAO detectionDAO; + private final StationDAO stationDAO; + + private final HttpClient client = HttpClient.newHttpClient(); + private final Logger logger = Logger.getLogger(Fetcher.class.getName()); + + + public HTTPFetcher(Jdbi database, Station station, Set lappers, Set positioners) { + this.batonDAO = database.onDemand(BatonDAO.class); + this.detectionDAO = database.onDemand(DetectionDAO.class); + this.stationDAO = database.onDemand(StationDAO.class); + + this.lappers = lappers; + this.positioners = positioners; + this.station = station; + } + + public void fetch() { + logger.info("Running Fetcher for station(" + this.station.getId() + ")"); + JsonBodyHandler bodyHandler = new JsonBodyHandler<>(RonnyResponse.class); + + while (true) { + //Update the station to account for possible changes in the database + this.stationDAO.getById(station.getId()).ifPresentOrElse( + station -> this.station = station, + () -> this.logger.severe("Can't update station from database.") + ); + + //Get last detection id + int lastDetectionId = 0; + Optional lastDetection = detectionDAO.latestDetectionByStationId(this.station.getId()); + if (lastDetection.isPresent()) { + lastDetectionId = lastDetection.get().getRemoteId(); + } + + //Create URL + URI url; + try { + url = new URI(station.getUrl() + "/detections/" + lastDetectionId); + } catch (URISyntaxException ex) { + this.logger.severe(ex.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + continue; + } + + //Create request + HttpRequest request; + try { + request = HttpRequest.newBuilder() + .uri(url) + .version(HttpClient.Version.HTTP_1_1) + .timeout(Duration.ofSeconds(Fetcher.REQUEST_TIMEOUT_S)) + .build(); + } catch (IllegalArgumentException e) { + logger.severe(e.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException ex) { + logger.severe(ex.getMessage()); + } + continue; + } + + //Do request + HttpResponse> response; + try { + try { + response = this.client.send(request, bodyHandler); + } catch (ConnectException | HttpConnectTimeoutException ex) { + this.logger.severe("Could not connect to " + request.uri()); + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + continue; + } catch (IOException e) { + logger.severe(e.getMessage()); + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + continue; + } + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + continue; + } + + //Check response state + if (response.statusCode() != 200) { + this.logger.warning( + "Unexpected status code(" + response.statusCode() + ") when requesting " + url + " for station(" + this.station.getName() + ")" + ); + continue; + } + + //Fetch all batons and create a map by batonMAC + Map baton_mac_map = batonDAO.getAll().stream() + .collect(Collectors.toMap(b -> b.getMac().toUpperCase(), Function.identity())); + + //Insert detections + List new_detections = new ArrayList<>(); + List detections = response.body().get().detections; + for (RonnyDetection detection : detections) { + if (baton_mac_map.containsKey(detection.mac.toUpperCase())) { + var baton = baton_mac_map.get(detection.mac.toUpperCase()); + new_detections.add(new Detection( + baton.getId(), + station.getId(), + detection.rssi, + detection.battery, + detection.uptimeMs, + detection.id, + new Timestamp((long) (detection.detectionTimestamp * 1000)), + new Timestamp(System.currentTimeMillis()) + )); + } + } + if (!new_detections.isEmpty()) { + detectionDAO.insertAll(new_detections); + new_detections.forEach((detection) -> { + lappers.forEach((lapper) -> lapper.handle(detection)); + positioners.forEach((positioner) -> positioner.handle(detection)); + }); + } + + this.logger.finer("Fetched " + detections.size() + " detections from " + station.getName() + ", Saved " + new_detections.size()); + + //If few detections are retrieved from the station, wait for some time. + if (detections.size() < Fetcher.FULL_BATCH_SIZE) { + try { + Thread.sleep(Fetcher.IDLE_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/telraam/station/JsonBodyHandler.java b/src/main/java/telraam/station/http/JsonBodyHandler.java similarity index 97% rename from src/main/java/telraam/station/JsonBodyHandler.java rename to src/main/java/telraam/station/http/JsonBodyHandler.java index 2d28e7f..462039f 100644 --- a/src/main/java/telraam/station/JsonBodyHandler.java +++ b/src/main/java/telraam/station/http/JsonBodyHandler.java @@ -1,4 +1,4 @@ -package telraam.station; +package telraam.station.http; import com.fasterxml.jackson.databind.ObjectMapper; @@ -17,12 +17,6 @@ public JsonBodyHandler(Class targetClass) { this.targetClass = targetClass; } - @Override - public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) { - return asJSON(this.targetClass); - } - - public static HttpResponse.BodySubscriber> asJSON(Class targetType) { HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream(); @@ -40,4 +34,9 @@ public static Supplier toSupplierOfType(InputStream inputStream, Class } }; } -} \ No newline at end of file + + @Override + public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) { + return asJSON(this.targetClass); + } +} diff --git a/src/main/java/telraam/station/models/RonnyResponse.java b/src/main/java/telraam/station/models/RonnyResponse.java index 726cafc..63e1382 100644 --- a/src/main/java/telraam/station/models/RonnyResponse.java +++ b/src/main/java/telraam/station/models/RonnyResponse.java @@ -9,4 +9,4 @@ public class RonnyResponse { @JsonProperty("station_id") public String stationRonnyName; -} +} \ No newline at end of file diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java new file mode 100644 index 0000000..25b7bb4 --- /dev/null +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -0,0 +1,75 @@ +package telraam.station.websocket; + +import jakarta.websocket.*; + +import java.net.URI; + +@ClientEndpoint +public class WebsocketClient { + public interface MessageHandler { + void handleMessage(String message); + } + public interface onStateChangeHandler { + void handleChange(); + } + + private URI endpoint; + private Session session = null; + private MessageHandler messageHandler; + private onStateChangeHandler onOpenHandler; + private onStateChangeHandler onCloseHandler; + + public WebsocketClient(URI endpointURI) throws RuntimeException { + this.endpoint = endpointURI; + } + + public void listen() throws RuntimeException { + try { + WebSocketContainer container = ContainerProvider.getWebSocketContainer(); + container.setDefaultMaxTextMessageBufferSize(100 * 1048576); // 100Mb + container.connectToServer(this, endpoint); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @OnOpen + public void onOpen(Session session) { + this.session = session; + if (this.onOpenHandler != null) { + this.onOpenHandler.handleChange(); + } + } + + @OnClose + public void onClose(Session userSession, CloseReason reason) { + this.session = null; + if (this.onCloseHandler != null) { + this.onCloseHandler.handleChange(); + } + } + + @OnMessage + public void onMessage(String message) { + if (this.messageHandler != null) { + this.messageHandler.handleMessage(message); + } + } + + public void addOnOpenHandler(onStateChangeHandler openHandler) { + this.onOpenHandler = openHandler; + } + + public void addOnCloseHandler(onStateChangeHandler openHandler) { + this.onCloseHandler = openHandler; + } + + public void addMessageHandler(MessageHandler msgHandler) { + this.messageHandler = msgHandler; + } + + public void sendMessage(String message) { + + this.session.getAsyncRemote().sendText(message); + } +} diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java new file mode 100644 index 0000000..285ad15 --- /dev/null +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -0,0 +1,165 @@ +package telraam.station.websocket; + +import com.fasterxml.jackson.core.JsonProcessingException; +import lombok.AllArgsConstructor; +import org.jdbi.v3.core.Jdbi; +import com.fasterxml.jackson.databind.ObjectMapper; +import telraam.database.daos.BatonDAO; +import telraam.database.daos.DetectionDAO; +import telraam.database.daos.StationDAO; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.logic.lapper.Lapper; +import telraam.logic.positioner.Positioner; +import telraam.station.Fetcher; +import telraam.station.models.RonnyDetection; + +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.*; +import java.sql.Timestamp; +import java.util.*; +import java.util.logging.Logger; + +public class WebsocketFetcher implements Fetcher { + private final Set lappers; + private final Set positioners; + private Station station; + + private final BatonDAO batonDAO; + private final DetectionDAO detectionDAO; + private final StationDAO stationDAO; + + private final HttpClient client = HttpClient.newHttpClient(); + private final Logger logger = Logger.getLogger(WebsocketFetcher.class.getName()); + + public WebsocketFetcher(Jdbi database, Station station, Set lappers, Set positioners) { + this.batonDAO = database.onDemand(BatonDAO.class); + this.detectionDAO = database.onDemand(DetectionDAO.class); + this.stationDAO = database.onDemand(StationDAO.class); + this.lappers = lappers; + this.positioners = positioners; + + this.station = station; + } + + public void fetch() { + logger.info("Running Fetcher for station(" + this.station.getId() + ")"); + ObjectMapper mapper = new ObjectMapper(); + + //Update the station to account for possible changes in the database + this.stationDAO.getById(station.getId()).ifPresentOrElse( + station -> this.station = station, + () -> this.logger.severe("Can't update station from database.") + ); + + //Get last detection id + int lastDetectionId = 0; + Optional lastDetection = detectionDAO.latestDetectionByStationId(this.station.getId()); + if (lastDetection.isPresent()) { + lastDetectionId = lastDetection.get().getRemoteId(); + } + + InitWSMessage wsMessage = new InitWSMessage(lastDetectionId); + String wsMessageEncoded; + try { + wsMessageEncoded = mapper.writeValueAsString(wsMessage); + } catch (JsonProcessingException e) { + logger.severe(e.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException ex) { + logger.severe(ex.getMessage()); + } + this.fetch(); + return; + } + + //Create URL + URI url; + try { + url = new URI(station.getUrl()); + } catch (URISyntaxException ex) { + this.logger.severe(ex.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + this.fetch(); + return; + } + + + WebsocketClient websocketClient = new WebsocketClient(url); + websocketClient.addOnOpenHandler(() -> { + websocketClient.sendMessage(wsMessageEncoded); + }); + websocketClient.addOnCloseHandler(() -> { + this.logger.severe(String.format("Websocket for station %s got closed", station.getName())); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + this.fetch(); + }); + websocketClient.addMessageHandler((String msg) -> { + //Insert detections + List new_detections = new ArrayList<>(); + List detection_mac_addresses = new ArrayList<>(); + + try { + List detections = Arrays.asList(mapper.readValue(msg, RonnyDetection[].class)); + for (RonnyDetection detection : detections) { + new_detections.add(new Detection( + 0, + station.getId(), + detection.rssi, + detection.battery, + detection.uptimeMs, + detection.id, + new Timestamp((long) (detection.detectionTimestamp * 1000)), + new Timestamp(System.currentTimeMillis()) + )); + detection_mac_addresses.add(detection.mac.toUpperCase()); + } + if (!new_detections.isEmpty()) { + List db_detections = detectionDAO.insertAllWithoutBaton(new_detections, detection_mac_addresses); + for(int i = 0; i < new_detections.size(); i++) { + Detection detection = new_detections.get(i); + Detection db_detection = db_detections.get(i); + + detection.setBatonId(db_detection.getBatonId()); + detection.setId(db_detection.getId()); + + lappers.forEach((lapper) -> lapper.handle(detection)); + positioners.forEach(positioner -> positioner.handle(detection)); + } + } + + logger.finer("Fetched " + detections.size() + " detections from " + station.getName() + ", Saved " + new_detections.size()); + } catch (JsonProcessingException e) { + logger.severe(e.getMessage()); + } + }); + + try { + websocketClient.listen(); + } catch (RuntimeException ex) { + this.logger.severe(ex.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + this.fetch(); + return; + } + } + + @AllArgsConstructor + private static class InitWSMessage { + public int lastId; + } +} From 19ee5c085e855941d67d6c07532b29c9ed1ebe19 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 20 Mar 2024 21:36:30 +0100 Subject: [PATCH 51/90] feat(station): send InitMessage on open connection --- src/main/java/telraam/station/Fetcher.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index 753474a..626e26e 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -11,4 +11,5 @@ public interface Fetcher { int IDLE_TIMEOUT_MS = 4000; // Wait 4 seconds void fetch(); + } From 44832744e0d918dc7a2f561cac6391f20b2983e1 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Fri, 29 Mar 2024 17:50:21 +0100 Subject: [PATCH 52/90] refactor: Use jakarta websockets --- src/main/java/telraam/station/Fetcher.java | 1 - .../java/telraam/station/WebsocketClient.java | 58 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/main/java/telraam/station/WebsocketClient.java diff --git a/src/main/java/telraam/station/Fetcher.java b/src/main/java/telraam/station/Fetcher.java index 626e26e..753474a 100644 --- a/src/main/java/telraam/station/Fetcher.java +++ b/src/main/java/telraam/station/Fetcher.java @@ -11,5 +11,4 @@ public interface Fetcher { int IDLE_TIMEOUT_MS = 4000; // Wait 4 seconds void fetch(); - } diff --git a/src/main/java/telraam/station/WebsocketClient.java b/src/main/java/telraam/station/WebsocketClient.java new file mode 100644 index 0000000..e57564a --- /dev/null +++ b/src/main/java/telraam/station/WebsocketClient.java @@ -0,0 +1,58 @@ +package telraam.station; + +import jakarta.websocket.*; + +import java.net.URI; + +@ClientEndpoint +public class WebsocketClient { + public interface MessageHandler { + void handleMessage(String message); + } + public interface OnOpenHandler { + void handleMsgOpen(); + } + + Session session = null; + private MessageHandler messageHandler; + private OnOpenHandler onOpenHandler; + + public WebsocketClient(URI endpointURI) { + try { + WebSocketContainer container = ContainerProvider.getWebSocketContainer(); + container.connectToServer(this, endpointURI); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @OnOpen + public void onOpen(Session session) { + this.session = session; + } + + @OnClose + public void onClose(Session userSession, CloseReason reason) { + System.out.println("closing websocket"); + this.session = null; + } + + @OnMessage + public void onMessage(String message) { + if (this.messageHandler != null) { + this.messageHandler.handleMessage(message); + } + } + + public void addOnOpenHandler(OnOpenHandler openHandler) { + this.onOpenHandler = openHandler; + } + + public void addMessageHandler(MessageHandler msgHandler) { + this.messageHandler = msgHandler; + } + + public void sendMessage(String message) { + this.session.getAsyncRemote().sendText(message); + } +} From d35f66b0c8f4434422d0a6dfe55556571ba981d7 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 2 Apr 2024 01:13:00 +0200 Subject: [PATCH 53/90] feat: re-add http fetcher & move WS to own package --- .../java/telraam/station/WebsocketClient.java | 58 ------------------- .../station/websocket/WebsocketClient.java | 1 - .../station/websocket/WebsocketFetcher.java | 1 - 3 files changed, 60 deletions(-) delete mode 100644 src/main/java/telraam/station/WebsocketClient.java diff --git a/src/main/java/telraam/station/WebsocketClient.java b/src/main/java/telraam/station/WebsocketClient.java deleted file mode 100644 index e57564a..0000000 --- a/src/main/java/telraam/station/WebsocketClient.java +++ /dev/null @@ -1,58 +0,0 @@ -package telraam.station; - -import jakarta.websocket.*; - -import java.net.URI; - -@ClientEndpoint -public class WebsocketClient { - public interface MessageHandler { - void handleMessage(String message); - } - public interface OnOpenHandler { - void handleMsgOpen(); - } - - Session session = null; - private MessageHandler messageHandler; - private OnOpenHandler onOpenHandler; - - public WebsocketClient(URI endpointURI) { - try { - WebSocketContainer container = ContainerProvider.getWebSocketContainer(); - container.connectToServer(this, endpointURI); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @OnOpen - public void onOpen(Session session) { - this.session = session; - } - - @OnClose - public void onClose(Session userSession, CloseReason reason) { - System.out.println("closing websocket"); - this.session = null; - } - - @OnMessage - public void onMessage(String message) { - if (this.messageHandler != null) { - this.messageHandler.handleMessage(message); - } - } - - public void addOnOpenHandler(OnOpenHandler openHandler) { - this.onOpenHandler = openHandler; - } - - public void addMessageHandler(MessageHandler msgHandler) { - this.messageHandler = msgHandler; - } - - public void sendMessage(String message) { - this.session.getAsyncRemote().sendText(message); - } -} diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java index 25b7bb4..a1ea217 100644 --- a/src/main/java/telraam/station/websocket/WebsocketClient.java +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -69,7 +69,6 @@ public void addMessageHandler(MessageHandler msgHandler) { } public void sendMessage(String message) { - this.session.getAsyncRemote().sendText(message); } } diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java index 285ad15..3d49016 100644 --- a/src/main/java/telraam/station/websocket/WebsocketFetcher.java +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -90,7 +90,6 @@ public void fetch() { return; } - WebsocketClient websocketClient = new WebsocketClient(url); websocketClient.addOnOpenHandler(() -> { websocketClient.sendMessage(wsMessageEncoded); From 607d73cf50ebd8eeabe5eab8d278bf142b0494bf Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 2 Apr 2024 01:16:31 +0200 Subject: [PATCH 54/90] fix(ws-fetcher): catch client creation error --- .../station/websocket/WebsocketFetcher.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java index 3d49016..b7eaf28 100644 --- a/src/main/java/telraam/station/websocket/WebsocketFetcher.java +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -90,7 +90,23 @@ public void fetch() { return; } - WebsocketClient websocketClient = new WebsocketClient(url); + + WebsocketClient websocketClient; + + try { + websocketClient = new WebsocketClient(url); + } catch (RuntimeException ex) { + this.logger.severe(ex.getMessage()); + try { + Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + this.fetch(); + return; + } + + websocketClient.addOnOpenHandler(() -> { websocketClient.sendMessage(wsMessageEncoded); }); From de43e915d6e13afc5f1b72bafd25ce0b7140fda8 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 2 Apr 2024 18:20:33 +0200 Subject: [PATCH 55/90] feat(ws-fetcher): open WS after setting handlers --- .../station/websocket/WebsocketClient.java | 1 + .../station/websocket/WebsocketFetcher.java | 18 ++++++------------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java index a1ea217..25b7bb4 100644 --- a/src/main/java/telraam/station/websocket/WebsocketClient.java +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -69,6 +69,7 @@ public void addMessageHandler(MessageHandler msgHandler) { } public void sendMessage(String message) { + this.session.getAsyncRemote().sendText(message); } } diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java index b7eaf28..24c78b4 100644 --- a/src/main/java/telraam/station/websocket/WebsocketFetcher.java +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -91,24 +91,18 @@ public void fetch() { } - WebsocketClient websocketClient; - - try { - websocketClient = new WebsocketClient(url); - } catch (RuntimeException ex) { - this.logger.severe(ex.getMessage()); + WebsocketClient websocketClient = new WebsocketClient(url); + websocketClient.addOnOpenHandler(() -> { + websocketClient.sendMessage(wsMessageEncoded); + }); + websocketClient.addOnCloseHandler(() -> { + this.logger.severe(String.format("Websocket for station %s got closed", station.getName())); try { Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); } catch (InterruptedException e) { logger.severe(e.getMessage()); } this.fetch(); - return; - } - - - websocketClient.addOnOpenHandler(() -> { - websocketClient.sendMessage(wsMessageEncoded); }); websocketClient.addOnCloseHandler(() -> { this.logger.severe(String.format("Websocket for station %s got closed", station.getName())); From e8245c3452200cc7c936bec727038c6628dc34c4 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 2 Apr 2024 18:21:21 +0200 Subject: [PATCH 56/90] feat(ws-fetcher): retrieve missing values for detections from DB & try to fix simplePositioner cursedness with threading --- .../positioner/simple/SimplePositioner.java | 103 ------------------ 1 file changed, 103 deletions(-) delete mode 100644 src/main/java/telraam/logic/positioner/simple/SimplePositioner.java diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java deleted file mode 100644 index 9958d1e..0000000 --- a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java +++ /dev/null @@ -1,103 +0,0 @@ -package telraam.logic.positioner.simple; - -import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonSwitchoverDAO; -import telraam.database.daos.StationDAO; -import telraam.database.daos.TeamDAO; -import telraam.database.models.BatonSwitchover; -import telraam.database.models.Detection; -import telraam.database.models.Station; -import telraam.database.models.Team; -import telraam.logic.positioner.CircularQueue; -import telraam.logic.positioner.Position; -import telraam.logic.positioner.PositionSender; -import telraam.logic.positioner.Positioner; - -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class SimplePositioner implements Positioner { - private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); - private final int QUEUE_SIZE = 50; - private final int MIN_RSSI = -85; - private final int DEBOUNCE_TIMEOUT = 1; - private boolean debounceScheduled; - private final ScheduledExecutorService scheduler; - private final PositionSender positionSender; - private final Map batonIdToTeam; - private final Map> teamDetections; - private final List stations; - private final Map teamPositions; - - public SimplePositioner(Jdbi jdbi) { - this.debounceScheduled = false; - this.scheduler = Executors.newScheduledThreadPool(1); - this.positionSender = new PositionSender(); - this.batonIdToTeam = new HashMap<>(); - this.teamDetections = new HashMap<>(); - this.teamPositions = new HashMap<>(); - - TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); - List teams = teamDAO.getAll(); - for (Team team : teams) { - teamDetections.put(team.getId(), new CircularQueue<>(QUEUE_SIZE)); - teamPositions.put(team.getId(), new Position(team.getId())); - } - List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); - switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); - - for (BatonSwitchover switchover : switchovers) { - batonIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); - } - - List stationList = jdbi.onDemand(StationDAO.class).getAll(); - stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); - stations = stationList.stream().map(Station::getId).toList(); - } - - public void calculatePositions() { - logger.info("SimplePositioner: Calculating positions..."); - for (Map.Entry> entry : teamDetections.entrySet()) { - List detections = teamDetections.get(entry.getKey()); - detections.sort(Comparator.comparing(Detection::getTimestamp)); - - int currentStationRssi = MIN_RSSI; - int currentStationPosition = 0; - for (Detection detection : detections) { - if (detection.getRssi() > currentStationRssi) { - currentStationRssi = detection.getRssi(); - currentStationPosition = detection.getStationId(); - } - } - - float progress = ((float) 100 / stations.size()) * currentStationPosition; - teamPositions.get(entry.getKey()).setProgress(progress); - } - - positionSender.send(teamPositions.values().stream().toList()); - logger.info("SimplePositioner: Done calculating positions"); - } - - public synchronized void handle(Detection detection) { - Team team = batonIdToTeam.get(detection.getBatonId()); - teamDetections.get(team.getId()).add(detection); - - if (!debounceScheduled) { - debounceScheduled = true; - scheduler.schedule(() -> { - try { - calculatePositions(); - } catch (Exception e) { - logger.log(Level.SEVERE, e.getMessage(), e); - } - debounceScheduled = false; - }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); - } - } -} From 8bcdffa5b0dac07277b00ae7fcb9e274a233fdd6 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Sat, 13 Apr 2024 14:40:53 +0200 Subject: [PATCH 57/90] fix(simplePositioner): make handle function synchronised --- .../positioner/simple/SimplePositioner.java | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/main/java/telraam/logic/positioner/simple/SimplePositioner.java diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java new file mode 100644 index 0000000..9958d1e --- /dev/null +++ b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java @@ -0,0 +1,103 @@ +package telraam.logic.positioner.simple; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.BatonSwitchover; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.database.models.Team; +import telraam.logic.positioner.CircularQueue; +import telraam.logic.positioner.Position; +import telraam.logic.positioner.PositionSender; +import telraam.logic.positioner.Positioner; + +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class SimplePositioner implements Positioner { + private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); + private final int QUEUE_SIZE = 50; + private final int MIN_RSSI = -85; + private final int DEBOUNCE_TIMEOUT = 1; + private boolean debounceScheduled; + private final ScheduledExecutorService scheduler; + private final PositionSender positionSender; + private final Map batonIdToTeam; + private final Map> teamDetections; + private final List stations; + private final Map teamPositions; + + public SimplePositioner(Jdbi jdbi) { + this.debounceScheduled = false; + this.scheduler = Executors.newScheduledThreadPool(1); + this.positionSender = new PositionSender(); + this.batonIdToTeam = new HashMap<>(); + this.teamDetections = new HashMap<>(); + this.teamPositions = new HashMap<>(); + + TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); + List teams = teamDAO.getAll(); + for (Team team : teams) { + teamDetections.put(team.getId(), new CircularQueue<>(QUEUE_SIZE)); + teamPositions.put(team.getId(), new Position(team.getId())); + } + List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); + switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); + + for (BatonSwitchover switchover : switchovers) { + batonIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); + } + + List stationList = jdbi.onDemand(StationDAO.class).getAll(); + stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); + stations = stationList.stream().map(Station::getId).toList(); + } + + public void calculatePositions() { + logger.info("SimplePositioner: Calculating positions..."); + for (Map.Entry> entry : teamDetections.entrySet()) { + List detections = teamDetections.get(entry.getKey()); + detections.sort(Comparator.comparing(Detection::getTimestamp)); + + int currentStationRssi = MIN_RSSI; + int currentStationPosition = 0; + for (Detection detection : detections) { + if (detection.getRssi() > currentStationRssi) { + currentStationRssi = detection.getRssi(); + currentStationPosition = detection.getStationId(); + } + } + + float progress = ((float) 100 / stations.size()) * currentStationPosition; + teamPositions.get(entry.getKey()).setProgress(progress); + } + + positionSender.send(teamPositions.values().stream().toList()); + logger.info("SimplePositioner: Done calculating positions"); + } + + public synchronized void handle(Detection detection) { + Team team = batonIdToTeam.get(detection.getBatonId()); + teamDetections.get(team.getId()).add(detection); + + if (!debounceScheduled) { + debounceScheduled = true; + scheduler.schedule(() -> { + try { + calculatePositions(); + } catch (Exception e) { + logger.log(Level.SEVERE, e.getMessage(), e); + } + debounceScheduled = false; + }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); + } + } +} From 6b44e356c2a40d1ae5ed9451431e79aaba8bfc27 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Mon, 1 Apr 2024 13:27:26 +0200 Subject: [PATCH 58/90] tmp --- .../nostradamus/CircularPriorityQueue.java | 28 +++ .../positioner/nostradamus/Nostradamus.java | 171 ++++++++++++++++++ .../positioner/nostradamus/TeamData.java | 23 +++ .../{ => simple}/CircularQueue.java | 2 +- .../positioner/simple/SimplePositioner.java | 3 +- .../telraam/websocket/WebSocketMessage.java | 3 +- 6 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/TeamData.java rename src/main/java/telraam/logic/positioner/{ => simple}/CircularQueue.java (89%) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java b/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java new file mode 100644 index 0000000..3ca788d --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java @@ -0,0 +1,28 @@ +package telraam.logic.positioner.nostradamus; + +import telraam.database.models.Detection; + +import java.util.Comparator; +import java.util.PriorityQueue; + +public class CircularPriorityQueue extends PriorityQueue { + private final int maxSize; + + // TODO: Check if in the right order. Oldest timestamp (the earliest) should be first + public CircularPriorityQueue(int maxSize) { + super(Comparator.comparing(Detection::getTimestamp)); + + this.maxSize = maxSize; + } + + @Override + public boolean add(Detection e) { + if (size() >= this.maxSize) { + if (e.getTimestamp().after(peek().getTimestamp())) { + remove(); + } + } + + return super.add(e); + } +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java new file mode 100644 index 0000000..d2dfcb8 --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -0,0 +1,171 @@ +package telraam.logic.positioner.nostradamus; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.BatonSwitchover; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.database.models.Team; +import telraam.logic.positioner.Position; +import telraam.logic.positioner.PositionSender; +import telraam.logic.positioner.Positioner; + +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class Nostradamus implements Positioner { + private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); + + private final int INTERVAL_FETCH = 10000; + private final int DEBOUNCE_TIMEOUT = 1; + private final int MAX_SIZE = 10000; + private final int MIN_RSSI = -85; + private final int INTERVAL = 2; + private final ScheduledExecutorService scheduler; + private boolean debounceScheduled; + private Lock lock; + + private final Jdbi jdbi; + private final TeamDAO teamDAO; + private final StationDAO stationDAO; + private final BatonSwitchoverDAO batonSwitchoverDAO; + private final PositionSender positionSender; + private Map teamDetections; + private Map teamData; + private Map batonIdToTeam; + private Map idToStation; + + public Nostradamus(Jdbi jdbi) { + this.scheduler = Executors.newScheduledThreadPool(1); + this.debounceScheduled = false; + this.lock = new ReentrantLock(); + + this.jdbi = jdbi; + this.teamDAO = jdbi.onDemand(TeamDAO.class); + this.stationDAO = jdbi.onDemand(StationDAO.class); + this.batonSwitchoverDAO = jdbi.onDemand(BatonSwitchoverDAO.class); + + this.positionSender = new PositionSender(); + + new Thread(this::fetch); + } + + // Update variables that depend on teams, stations and / or batonswitchover + private void fetch() { + while (true) { + List teams = teamDAO.getAll(); + List switchovers = batonSwitchoverDAO.getAll(); + List stations = stationDAO.getAll(); + + lock.lock(); + + teamDetections = teams.stream() + .collect( + Collectors.toMap( + team -> team, + team -> teamDetections.getOrDefault(team, new CircularPriorityQueue(MAX_SIZE)) + ) + ); + teamData = teams.stream() + .collect( + Collectors.toMap( + team -> team, + team -> teamData.getOrDefault(team, new TeamData(team.getId())) + ) + ); + batonIdToTeam = switchovers.stream() + .collect( + Collectors.toMap( + BatonSwitchover::getNewBatonId, + switchover -> teamDAO.getById(switchover.getTeamId()).get() + ) + ); + idToStation = stations.stream() + .collect( + Collectors.toMap( + Station::getId, + station -> station + ) + ); + + lock.unlock(); + + try { + Thread.sleep(INTERVAL_FETCH); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + } + + // TODO: Add more detection filtering, high enough rssi, only one detection / timestamp, ... + // TODO: Calculate average times in separate thread + // TODO: If multiple detections come out of order -> restart + // TODO: If something in fetch changes -> restart + + // TODO: Start simple, if arrives at new station -> send location and average time. Else send location given speed + private void calculatePositions() { + logger.info("Nostradamus: Calculating positions..."); + + for (Map.Entry entry: teamDetections.entrySet()) { + Map averageTimes = new HashMap<>(); + + int lastStationid = -1; + long currentStationTime = 0; + int currentStationRssi = MIN_RSSI; + int currentStationId = 0; + + for (Detection detection: entry.getValue()) { + if (detection.getTimestamp().getTime() - currentStationTime < INTERVAL) { + // Same interval + // Keep station with the highest RSSI + if (detection.getRssi() > currentStationRssi) { + currentStationId = detection.getStationId(); + currentStationRssi = detection.getRssi(); + } + } else { + // New interval + // Save old station id + lastStationid = currentStationId; + currentStationTime = detection.getTimestamp().getTime(); + currentStationRssi = detection.getRssi(); + currentStationId = detection.getStationId(); + } + } + + // Keep result of last interval if it exists + Station currentStation = idToStation.getOrDefault(lastStationid, idToStation.get(currentStationId)); + + + } + + positionSender.send(teamData.values().stream().map(TeamData::getPosition).toList()); + logger.info("Nostradamus: Done calculating positions"); + } + + @Override + public void handle(Detection detection) { + Team team = batonIdToTeam.get(detection.getBatonId()); + teamDetections.get(team).add(detection); + + if (! debounceScheduled) { + debounceScheduled = true; + scheduler.schedule(() -> { + try { + calculatePositions(); + } catch (Exception e) { + logger.severe(e.getMessage()); + } + debounceScheduled = false; + }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); + } + } +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java new file mode 100644 index 0000000..cdb2eff --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -0,0 +1,23 @@ +package telraam.logic.positioner.nostradamus; + +import lombok.Getter; +import lombok.Setter; +import telraam.database.models.Station; +import telraam.logic.positioner.Position; + +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.Map; + +@Getter @Setter +public class TeamData { + private Position position; + private Station lastStation; + private Timestamp lastUpdate; + + public TeamData(int teamId) { + this.position = new Position(teamId); + this.lastStation = null; + this.lastUpdate = null; + } +} diff --git a/src/main/java/telraam/logic/positioner/CircularQueue.java b/src/main/java/telraam/logic/positioner/simple/CircularQueue.java similarity index 89% rename from src/main/java/telraam/logic/positioner/CircularQueue.java rename to src/main/java/telraam/logic/positioner/simple/CircularQueue.java index 773c633..ae101ed 100644 --- a/src/main/java/telraam/logic/positioner/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/simple/CircularQueue.java @@ -1,4 +1,4 @@ -package telraam.logic.positioner; +package telraam.logic.positioner.simple; import java.util.LinkedList; diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java index 9958d1e..fa6a395 100644 --- a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java +++ b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java @@ -8,7 +8,6 @@ import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.database.models.Team; -import telraam.logic.positioner.CircularQueue; import telraam.logic.positioner.Position; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; @@ -61,7 +60,7 @@ public SimplePositioner(Jdbi jdbi) { stations = stationList.stream().map(Station::getId).toList(); } - public void calculatePositions() { + private void calculatePositions() { logger.info("SimplePositioner: Calculating positions..."); for (Map.Entry> entry : teamDetections.entrySet()) { List detections = teamDetections.get(entry.getKey()); diff --git a/src/main/java/telraam/websocket/WebSocketMessage.java b/src/main/java/telraam/websocket/WebSocketMessage.java index 0b4200f..b280ec2 100644 --- a/src/main/java/telraam/websocket/WebSocketMessage.java +++ b/src/main/java/telraam/websocket/WebSocketMessage.java @@ -1,9 +1,10 @@ package telraam.websocket; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; -@Getter @Setter +@Getter @Setter @NoArgsConstructor public class WebSocketMessage { private String topic; private T data; From 91811a70abcd629277b9bf3d88792a3d73e19080 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Mon, 8 Apr 2024 17:45:21 +0200 Subject: [PATCH 59/90] refactor --- .../telraam/database/models/Detection.java | 6 + .../nostradamus/CircularPriorityQueue.java | 28 --- .../positioner/nostradamus/CircularQueue.java | 21 +++ .../positioner/nostradamus/Nostradamus.java | 171 ++++-------------- .../positioner/nostradamus/PositionList.java | 55 ++++++ .../positioner/nostradamus/TeamData.java | 52 +++++- 6 files changed, 165 insertions(+), 168 deletions(-) delete mode 100644 src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/PositionList.java diff --git a/src/main/java/telraam/database/models/Detection.java b/src/main/java/telraam/database/models/Detection.java index 5cd050b..4950feb 100644 --- a/src/main/java/telraam/database/models/Detection.java +++ b/src/main/java/telraam/database/models/Detection.java @@ -31,4 +31,10 @@ public Detection(Integer batonId, Integer stationId, Integer rssi, Float battery this.timestamp = timestamp; this.timestampIngestion = timestampIngestion; } + + public Detection(Integer id, Integer stationId, Integer rssi) { + this.id = id; + this.stationId = stationId; + this.rssi = rssi; + } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java b/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java deleted file mode 100644 index 3ca788d..0000000 --- a/src/main/java/telraam/logic/positioner/nostradamus/CircularPriorityQueue.java +++ /dev/null @@ -1,28 +0,0 @@ -package telraam.logic.positioner.nostradamus; - -import telraam.database.models.Detection; - -import java.util.Comparator; -import java.util.PriorityQueue; - -public class CircularPriorityQueue extends PriorityQueue { - private final int maxSize; - - // TODO: Check if in the right order. Oldest timestamp (the earliest) should be first - public CircularPriorityQueue(int maxSize) { - super(Comparator.comparing(Detection::getTimestamp)); - - this.maxSize = maxSize; - } - - @Override - public boolean add(Detection e) { - if (size() >= this.maxSize) { - if (e.getTimestamp().after(peek().getTimestamp())) { - remove(); - } - } - - return super.add(e); - } -} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java b/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java new file mode 100644 index 0000000..997e9bf --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java @@ -0,0 +1,21 @@ +package telraam.logic.positioner.nostradamus; + +import java.util.LinkedList; + +public class CircularQueue extends LinkedList { + + private final int maxSize; + public CircularQueue(int maxSize) { + this.maxSize = maxSize; + } + + @Override + public boolean add(T e) { + if (size() >= this.maxSize) { + removeFirst(); + } + + return super.add(e); + } + +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index d2dfcb8..c4524bc 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -1,171 +1,78 @@ package telraam.logic.positioner.nostradamus; import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonSwitchoverDAO; -import telraam.database.daos.StationDAO; -import telraam.database.daos.TeamDAO; -import telraam.database.models.BatonSwitchover; import telraam.database.models.Detection; -import telraam.database.models.Station; import telraam.database.models.Team; -import telraam.logic.positioner.Position; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; -import java.util.stream.Collectors; public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); - - private final int INTERVAL_FETCH = 10000; - private final int DEBOUNCE_TIMEOUT = 1; - private final int MAX_SIZE = 10000; - private final int MIN_RSSI = -85; - private final int INTERVAL = 2; - private final ScheduledExecutorService scheduler; - private boolean debounceScheduled; - private Lock lock; - - private final Jdbi jdbi; - private final TeamDAO teamDAO; - private final StationDAO stationDAO; - private final BatonSwitchoverDAO batonSwitchoverDAO; + private final int INTERVAL_CALCULATE = 500; // How often to handle new detections + private final int INTERVAL_FETCH = 30000; // Interval between fetching all stations, teams, ... + private final int INTERVAL_DETECTIONS = 1; // Amount of seconds to group detections by + private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals + private final int MIN_RSSI = -84; + private final List newDetections; // Contains not yet handled detections + private final Lock detectionLock; + private Map batonToTeam; // Baton ID to Team + private Map teamData; // All team data private final PositionSender positionSender; - private Map teamDetections; - private Map teamData; - private Map batonIdToTeam; - private Map idToStation; public Nostradamus(Jdbi jdbi) { - this.scheduler = Executors.newScheduledThreadPool(1); - this.debounceScheduled = false; - this.lock = new ReentrantLock(); - - this.jdbi = jdbi; - this.teamDAO = jdbi.onDemand(TeamDAO.class); - this.stationDAO = jdbi.onDemand(StationDAO.class); - this.batonSwitchoverDAO = jdbi.onDemand(BatonSwitchoverDAO.class); + this.newDetections = new ArrayList<>(); + this.detectionLock = new ReentrantLock(); // TODO: Right kind of lock? this.positionSender = new PositionSender(); - new Thread(this::fetch); + new Thread(this::calculatePosition); } - // Update variables that depend on teams, stations and / or batonswitchover - private void fetch() { + private void calculatePosition() { + Set changedTeams = new HashSet<>(); // List of teams that have changed station while (true) { - List teams = teamDAO.getAll(); - List switchovers = batonSwitchoverDAO.getAll(); - List stations = stationDAO.getAll(); - - lock.lock(); + changedTeams.clear(); + detectionLock.lock(); + for (Detection detection: newDetections) { + if (batonToTeam.containsKey(detection.getBatonId())) { + Team team = batonToTeam.get(detection.getBatonId()); + if (teamData.containsKey(team) && teamData.get(team).addDetection(detection)) { + changedTeams.add(team); + } + } + } + detectionLock.unlock(); // Use lock as short as possible - teamDetections = teams.stream() - .collect( - Collectors.toMap( - team -> team, - team -> teamDetections.getOrDefault(team, new CircularPriorityQueue(MAX_SIZE)) - ) - ); - teamData = teams.stream() - .collect( - Collectors.toMap( - team -> team, - team -> teamData.getOrDefault(team, new TeamData(team.getId())) - ) - ); - batonIdToTeam = switchovers.stream() - .collect( - Collectors.toMap( - BatonSwitchover::getNewBatonId, - switchover -> teamDAO.getById(switchover.getTeamId()).get() - ) - ); - idToStation = stations.stream() - .collect( - Collectors.toMap( - Station::getId, - station -> station - ) - ); + if (!changedTeams.isEmpty()) { + // Update + for (Team team: changedTeams) { + teamData.get(team).updatePosition(); + } - lock.unlock(); + positionSender.send( + changedTeams.stream().map(team -> teamData.get(team).getPosition()).toList() + ); + } try { - Thread.sleep(INTERVAL_FETCH); + Thread.sleep(INTERVAL_CALCULATE); } catch (InterruptedException e) { logger.severe(e.getMessage()); } } } - // TODO: Add more detection filtering, high enough rssi, only one detection / timestamp, ... - // TODO: Calculate average times in separate thread - // TODO: If multiple detections come out of order -> restart - // TODO: If something in fetch changes -> restart - - // TODO: Start simple, if arrives at new station -> send location and average time. Else send location given speed - private void calculatePositions() { - logger.info("Nostradamus: Calculating positions..."); - - for (Map.Entry entry: teamDetections.entrySet()) { - Map averageTimes = new HashMap<>(); - - int lastStationid = -1; - long currentStationTime = 0; - int currentStationRssi = MIN_RSSI; - int currentStationId = 0; - - for (Detection detection: entry.getValue()) { - if (detection.getTimestamp().getTime() - currentStationTime < INTERVAL) { - // Same interval - // Keep station with the highest RSSI - if (detection.getRssi() > currentStationRssi) { - currentStationId = detection.getStationId(); - currentStationRssi = detection.getRssi(); - } - } else { - // New interval - // Save old station id - lastStationid = currentStationId; - currentStationTime = detection.getTimestamp().getTime(); - currentStationRssi = detection.getRssi(); - currentStationId = detection.getStationId(); - } - } - - // Keep result of last interval if it exists - Station currentStation = idToStation.getOrDefault(lastStationid, idToStation.get(currentStationId)); - - - } - - positionSender.send(teamData.values().stream().map(TeamData::getPosition).toList()); - logger.info("Nostradamus: Done calculating positions"); - } - @Override public void handle(Detection detection) { - Team team = batonIdToTeam.get(detection.getBatonId()); - teamDetections.get(team).add(detection); - - if (! debounceScheduled) { - debounceScheduled = true; - scheduler.schedule(() -> { - try { - calculatePositions(); - } catch (Exception e) { - logger.severe(e.getMessage()); - } - debounceScheduled = false; - }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); + if (detection.getRssi() > MIN_RSSI) { + detectionLock.lock(); + newDetections.add(detection); + detectionLock.unlock(); } } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java new file mode 100644 index 0000000..e10540d --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java @@ -0,0 +1,55 @@ +package telraam.logic.positioner.nostradamus; + +import lombok.Getter; +import telraam.database.models.Detection; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Comparator; + +public class PositionList extends ArrayList { + + private final int interval; + @Getter + private Detection currentPosition; + private Timestamp newestDetection; + + public PositionList(int interval) { + this.interval = interval; + this.currentPosition = new Detection(-1, 0, -100); + this.newestDetection = new Timestamp(0); + } + + /** + * @param e element to add + * @return True if the current position has changed + */ + @Override + public boolean add(Detection e) { + super.add(e); + + if (e.getTimestamp().after(newestDetection)) { + newestDetection = e.getTimestamp(); + } + + if (!e.getStationId().equals(currentPosition.getStationId())) { + // Possible new position + if (e.getRssi() > currentPosition.getRssi() || !inInterval(currentPosition.getTimestamp(), newestDetection)) { + // Detection stored in currentPosition will change + int oldPosition = currentPosition.getStationId(); + // Filter out old detections + removeIf(detection -> !inInterval(detection.getTimestamp(), newestDetection)); + // Get new position + currentPosition = stream().max(Comparator.comparing(Detection::getRssi)).get(); + + return oldPosition != currentPosition.getStationId(); + } + } + + return false; + } + + private boolean inInterval(Timestamp oldest, Timestamp newest) { + return newest.getNanos() - oldest.getNanos() > interval; + } +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index cdb2eff..39547d2 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -1,23 +1,59 @@ package telraam.logic.positioner.nostradamus; import lombok.Getter; -import lombok.Setter; +import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.logic.positioner.Position; -import java.sql.Timestamp; import java.util.HashMap; +import java.util.List; import java.util.Map; -@Getter @Setter public class TeamData { + private PositionList detections; + private List stations; // Station list, ordered by distance from start + private Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. + private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times + @Getter private Position position; - private Station lastStation; - private Timestamp lastUpdate; + private Station currentStation; + private int totalDistance; - public TeamData(int teamId) { + + public TeamData(int teamId, int interval, List stations, int averageAmount) { + this.detections = new PositionList(interval); + this.stations = stations; + + averageTimes = new HashMap<>(); + for (Station station: stations) { + averageTimes.put(station.getId(), new CircularQueue<>(averageAmount)); + } + + this.previousStationArrival = System.currentTimeMillis(); this.position = new Position(teamId); - this.lastStation = null; - this.lastUpdate = null; + } + + public boolean addDetection(Detection e) { + boolean newStation = detections.add(e); + Station previousStation = detections.getCurrentPosition().getStationId() + + // TODO: If station missed big problem + if (newStation && averageTimes.containsKey(detections.getCurrentPosition())) { + long now = System.currentTimeMillis(); + averageTimes.get(detections.getCurrentPosition()).add(now - previousStationArrival); + previousStationArrival = now; + } + + return newStation; + } + + // TODO: Requires the last station to be on the finish. Convert to variable + public void updatePosition() { + float progress = (float) (currentStation.getDistanceFromStart() / totalDistance); + Station nextStation = stations.get(stations.indexOf(currentStation) + 1 % stations.size()); + + + + position.setProgress(progress); } } From dd4ff537188830a0d9bdeb79c7e2923d752662be Mon Sep 17 00:00:00 2001 From: Topvennie Date: Mon, 8 Apr 2024 23:09:03 +0200 Subject: [PATCH 60/90] nostradamus basic logic --- .../java/telraam/database/models/Station.java | 4 ++ .../telraam/logic/positioner/Position.java | 11 ++-- .../positioner/nostradamus/Nostradamus.java | 63 +++++++++++++++++-- .../positioner/nostradamus/TeamData.java | 59 ++++++++++------- 4 files changed, 105 insertions(+), 32 deletions(-) diff --git a/src/main/java/telraam/database/models/Station.java b/src/main/java/telraam/database/models/Station.java index 442e412..b1f1220 100644 --- a/src/main/java/telraam/database/models/Station.java +++ b/src/main/java/telraam/database/models/Station.java @@ -35,4 +35,8 @@ public Station(String name, boolean isBroken) { this.name = name; this.broken = isBroken; } + + public Station(Integer id) { + this.id = id; + } } diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 3a4218e..300837f 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -2,18 +2,21 @@ import lombok.Getter; import lombok.Setter; -import telraam.database.models.Team; -import telraam.websocket.WebSocketMessageSingleton; @Getter @Setter public class Position { private int teamId; - private float progress; // Progress of the lap. Between 0-1 - private float speed; // Current speed. Progress / second + private double progress; // Progress of the lap. Between 0-1 + private double speed; // Current speed. progress / second public Position(int teamId) { this.teamId = teamId; this.progress = 0; this.speed = 0; } + + public void update(double progress, double speed) { + this.progress = progress; + this.speed = speed; + } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index c4524bc..0d8e363 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -1,8 +1,11 @@ package telraam.logic.positioner.nostradamus; import org.jdbi.v3.core.Jdbi; -import telraam.database.models.Detection; -import telraam.database.models.Team; +import telraam.database.daos.BatonDAO; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.StationDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.*; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; @@ -10,42 +13,88 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; +import java.util.stream.Collectors; public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); private final int INTERVAL_CALCULATE = 500; // How often to handle new detections - private final int INTERVAL_FETCH = 30000; // Interval between fetching all stations, teams, ... + private final int INTERVAL_FETCH = 60000; // Interval between fetching all stations, teams, ... private final int INTERVAL_DETECTIONS = 1; // Amount of seconds to group detections by private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals private final int MIN_RSSI = -84; + private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections private final Lock detectionLock; + private final Lock dataLock; private Map batonToTeam; // Baton ID to Team private Map teamData; // All team data private final PositionSender positionSender; public Nostradamus(Jdbi jdbi) { + this.jdbi = jdbi; this.newDetections = new ArrayList<>(); - this.detectionLock = new ReentrantLock(); // TODO: Right kind of lock? + this.detectionLock = new ReentrantLock(); + this.dataLock = new ReentrantLock(); + + // Will be filled by fetch + this.batonToTeam = new HashMap<>(); + setTeamData(); this.positionSender = new PositionSender(); + new Thread(this::fetch); new Thread(this::calculatePosition); } + private void setTeamData() { + List stations = jdbi.onDemand(StationDAO.class).getAll(); + List teams = jdbi.onDemand(TeamDAO.class).getAll(); + + teamData = teams.stream().collect(Collectors.toMap( + team -> team, + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS, stations, AVERAGE_AMOUNT) + )); + } + + private void fetch() { + List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); + List teams = jdbi.onDemand(TeamDAO.class).getAll(); + + Map teamIdToTeam = teams.stream().collect(Collectors.toMap(Team::getId, team -> team)); + Map batonToTeam = switchovers.stream().collect(Collectors.toMap( + BatonSwitchover::getNewBatonId, + switchover -> teamIdToTeam.get(switchover.getTeamId()) + )); + + if (!this.batonToTeam.equals(batonToTeam)) { + dataLock.lock(); + this.batonToTeam = batonToTeam; + dataLock.unlock(); + } + + // zzzzzzzz + try { + Thread.sleep(INTERVAL_FETCH); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + private void calculatePosition() { Set changedTeams = new HashSet<>(); // List of teams that have changed station while (true) { + dataLock.lock(); changedTeams.clear(); detectionLock.lock(); for (Detection detection: newDetections) { if (batonToTeam.containsKey(detection.getBatonId())) { Team team = batonToTeam.get(detection.getBatonId()); - if (teamData.containsKey(team) && teamData.get(team).addDetection(detection)) { + if (teamData.get(team).addDetection(detection)) { changedTeams.add(team); } } } + newDetections.clear(); detectionLock.unlock(); // Use lock as short as possible if (!changedTeams.isEmpty()) { @@ -54,11 +103,15 @@ private void calculatePosition() { teamData.get(team).updatePosition(); } + // Send new data to the websocket positionSender.send( changedTeams.stream().map(team -> teamData.get(team).getPosition()).toList() ); } + dataLock.unlock(); + + // zzzzzzzz try { Thread.sleep(INTERVAL_CALCULATE); } catch (InterruptedException e) { diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 39547d2..9f3c0be 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -5,55 +5,68 @@ import telraam.database.models.Station; import telraam.logic.positioner.Position; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; public class TeamData { - private PositionList detections; - private List stations; // Station list, ordered by distance from start - private Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. + private final PositionList detections; + private final List stations; // Station list, ordered by distance from start + private final Map idToStation; // Map going from a station id to the station + private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times + private Station currentStation; // Current station location + private Station previousStation; // Previous station location + private final Double totalDistance; @Getter - private Position position; - private Station currentStation; - private int totalDistance; + private final Position position; public TeamData(int teamId, int interval, List stations, int averageAmount) { this.detections = new PositionList(interval); this.stations = stations; - - averageTimes = new HashMap<>(); - for (Station station: stations) { - averageTimes.put(station.getId(), new CircularQueue<>(averageAmount)); - } - + this.stations.sort(Comparator.comparing(Station::getDistanceFromStart)); + this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); + this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); this.previousStationArrival = System.currentTimeMillis(); + this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station + this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start this.position = new Position(teamId); } public boolean addDetection(Detection e) { boolean newStation = detections.add(e); - Station previousStation = detections.getCurrentPosition().getStationId() - // TODO: If station missed big problem - if (newStation && averageTimes.containsKey(detections.getCurrentPosition())) { - long now = System.currentTimeMillis(); - averageTimes.get(detections.getCurrentPosition()).add(now - previousStationArrival); - previousStationArrival = now; + if (newStation) { + previousStation = currentStation; + currentStation = idToStation.get(e.getStationId()); + if (isNextStation()) { + // Only add the time if it goes forward by exactly one station + averageTimes.get(previousStation).add(System.currentTimeMillis() - previousStationArrival); + } + previousStationArrival = System.currentTimeMillis(); } return newStation; } - // TODO: Requires the last station to be on the finish. Convert to variable - public void updatePosition() { - float progress = (float) (currentStation.getDistanceFromStart() / totalDistance); - Station nextStation = stations.get(stations.indexOf(currentStation) + 1 % stations.size()); + private boolean isNextStation() { + return (stations.indexOf(currentStation) - stations.indexOf(previousStation) + stations.size()) % stations.size() == 1; + } + // TODO: Smoothen out + public void updatePosition() { + double progress = currentStation.getDistanceFromStart() / totalDistance; + Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); + double distance = (nextStation.getDistanceFromStart() - currentStation.getDistanceFromStart() + totalDistance) % totalDistance; + double speed = ((distance / totalDistance) - progress) / getAverage(); // Progress / second + position.update(progress, speed); + } - position.setProgress(progress); + private double getAverage() { + return averageTimes.get(currentStation).stream().mapToDouble(time -> time).average().orElse(0.1); } } From 0e59e398af921e00387e75fda550371a98bc02a1 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 12 Apr 2024 14:56:14 +0200 Subject: [PATCH 61/90] chore: bugfixes --- src/main/java/telraam/App.java | 4 +- .../telraam/logic/positioner/Position.java | 5 +++ .../positioner/nostradamus/Nostradamus.java | 44 ++++++++++--------- .../positioner/nostradamus/PositionList.java | 15 +++++-- .../positioner/nostradamus/TeamData.java | 37 +++++++++++----- 5 files changed, 69 insertions(+), 36 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 08a3847..0d79b23 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -24,6 +24,7 @@ import telraam.logic.lapper.robust.RobustLapper; import telraam.logic.lapper.slapper.Slapper; import telraam.logic.positioner.Positioner; +import telraam.logic.positioner.nostradamus.Nostradamus; import telraam.logic.positioner.simple.SimplePositioner; import telraam.station.FetcherFactory; import telraam.station.websocket.WebsocketFetcher; @@ -142,7 +143,8 @@ public void run(AppConfiguration configuration, Environment environment) { // Set up positioners Set positioners = new HashSet<>(); - positioners.add(new SimplePositioner(this.database)); +// positioners.add(new SimplePositioner(this.database)); + positioners.add(new Nostradamus(this.database)); // Start fetch thread for each station FetcherFactory fetcherFactory = new FetcherFactory(this.database, lappers, positioners); diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 300837f..8a10da9 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -3,20 +3,25 @@ import lombok.Getter; import lombok.Setter; +import java.sql.Timestamp; + @Getter @Setter public class Position { private int teamId; private double progress; // Progress of the lap. Between 0-1 private double speed; // Current speed. progress / second + private long unix; public Position(int teamId) { this.teamId = teamId; this.progress = 0; this.speed = 0; + this.unix = 0; } public void update(double progress, double speed) { this.progress = progress; this.speed = speed; + this.unix = System.currentTimeMillis() / 1000L;; } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 0d8e363..0e1230c 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -17,17 +17,18 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); - private final int INTERVAL_CALCULATE = 500; // How often to handle new detections - private final int INTERVAL_FETCH = 60000; // Interval between fetching all stations, teams, ... - private final int INTERVAL_DETECTIONS = 1; // Amount of seconds to group detections by + private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections + private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching all stations, teams, ... + private final int INTERVAL_DETECTIONS_MS = 1000; // Amount of seconds to group detections by private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals + private final double AVERAGE_SPRINTING_SPEED_M_S = 6.84; // Average sprinting speed m / s private final int MIN_RSSI = -84; private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections private final Lock detectionLock; private final Lock dataLock; - private Map batonToTeam; // Baton ID to Team - private Map teamData; // All team data + private Map batonToTeam; // Baton ID to Team ID + private Map teamData; // All team data private final PositionSender positionSender; public Nostradamus(Jdbi jdbi) { @@ -42,8 +43,8 @@ public Nostradamus(Jdbi jdbi) { this.positionSender = new PositionSender(); - new Thread(this::fetch); - new Thread(this::calculatePosition); + new Thread(this::fetch).start(); + new Thread(this::calculatePosition).start(); } private void setTeamData() { @@ -51,19 +52,20 @@ private void setTeamData() { List teams = jdbi.onDemand(TeamDAO.class).getAll(); teamData = teams.stream().collect(Collectors.toMap( - team -> team, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS, stations, AVERAGE_AMOUNT) + Team::getId, + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_S) )); } private void fetch() { List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); - List teams = jdbi.onDemand(TeamDAO.class).getAll(); - Map teamIdToTeam = teams.stream().collect(Collectors.toMap(Team::getId, team -> team)); - Map batonToTeam = switchovers.stream().collect(Collectors.toMap( + Map batonToTeam = switchovers.stream().sorted( + Comparator.comparing(BatonSwitchover::getTimestamp) + ).collect(Collectors.toMap( BatonSwitchover::getNewBatonId, - switchover -> teamIdToTeam.get(switchover.getTeamId()) + BatonSwitchover::getTeamId, + (existing, replacement) -> replacement )); if (!this.batonToTeam.equals(batonToTeam)) { @@ -74,23 +76,23 @@ private void fetch() { // zzzzzzzz try { - Thread.sleep(INTERVAL_FETCH); + Thread.sleep(INTERVAL_FETCH_MS); } catch (InterruptedException e) { logger.severe(e.getMessage()); } } private void calculatePosition() { - Set changedTeams = new HashSet<>(); // List of teams that have changed station + Set changedTeams = new HashSet<>(); // List of teams that have changed station while (true) { dataLock.lock(); changedTeams.clear(); detectionLock.lock(); for (Detection detection: newDetections) { if (batonToTeam.containsKey(detection.getBatonId())) { - Team team = batonToTeam.get(detection.getBatonId()); - if (teamData.get(team).addDetection(detection)) { - changedTeams.add(team); + Integer teamId = batonToTeam.get(detection.getBatonId()); + if (teamData.get(teamId).addDetection(detection)) { + changedTeams.add(teamId); } } } @@ -99,8 +101,8 @@ private void calculatePosition() { if (!changedTeams.isEmpty()) { // Update - for (Team team: changedTeams) { - teamData.get(team).updatePosition(); + for (Integer teamId: changedTeams) { + teamData.get(teamId).updatePosition(); } // Send new data to the websocket @@ -113,7 +115,7 @@ private void calculatePosition() { // zzzzzzzz try { - Thread.sleep(INTERVAL_CALCULATE); + Thread.sleep(INTERVAL_CALCULATE_MS); } catch (InterruptedException e) { logger.severe(e.getMessage()); } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java index e10540d..7be0fa8 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java @@ -2,20 +2,24 @@ import lombok.Getter; import telraam.database.models.Detection; +import telraam.database.models.Station; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Comparator; +import java.util.List; public class PositionList extends ArrayList { private final int interval; + private final List stations; @Getter private Detection currentPosition; private Timestamp newestDetection; - public PositionList(int interval) { + public PositionList(int interval, List stations) { this.interval = interval; + this.stations = stations.stream().sorted(Comparator.comparing(Station::getDistanceFromStart)).map(Station::getId).toList(); this.currentPosition = new Detection(-1, 0, -100); this.newestDetection = new Timestamp(0); } @@ -32,13 +36,14 @@ public boolean add(Detection e) { newestDetection = e.getTimestamp(); } - if (!e.getStationId().equals(currentPosition.getStationId())) { + if (!e.getStationId().equals(currentPosition.getStationId()) && stationAfter(currentPosition.getStationId(), e.getStationId())) { // Possible new position if (e.getRssi() > currentPosition.getRssi() || !inInterval(currentPosition.getTimestamp(), newestDetection)) { // Detection stored in currentPosition will change int oldPosition = currentPosition.getStationId(); // Filter out old detections removeIf(detection -> !inInterval(detection.getTimestamp(), newestDetection)); + // Get new position currentPosition = stream().max(Comparator.comparing(Detection::getRssi)).get(); @@ -49,7 +54,11 @@ public boolean add(Detection e) { return false; } + private boolean stationAfter(int oldStationId, int newStationId) { + return (stations.indexOf(newStationId) - stations.indexOf(oldStationId) + stations.size()) % stations.size() > 0; + } + private boolean inInterval(Timestamp oldest, Timestamp newest) { - return newest.getNanos() - oldest.getNanos() > interval; + return newest.getTime() - oldest.getTime() < interval; } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 9f3c0be..03c554e 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -5,10 +5,7 @@ import telraam.database.models.Station; import telraam.logic.positioner.Position; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; public class TeamData { @@ -24,16 +21,31 @@ public class TeamData { private final Position position; - public TeamData(int teamId, int interval, List stations, int averageAmount) { - this.detections = new PositionList(interval); + public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed) { this.stations = stations; this.stations.sort(Comparator.comparing(Station::getDistanceFromStart)); + this.detections = new PositionList(interval, this.stations); this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); - this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); +// this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); this.previousStationArrival = System.currentTimeMillis(); this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start this.position = new Position(teamId); + this.averageTimes = getAverageTimes(averageAmount, sprintingSpeed); + } + + // Construct the average times and add a default value + // TODO: Populate with existing detections + private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { + Map> averageTimes = new HashMap<>(); + for (Station station: stations) { + int index = stations.indexOf(station); + averageTimes.put(station, new CircularQueue<>(averageAmount)); + double distance = (stations.get((index + 1) % stations.size()).getDistanceFromStart() - station.getDistanceFromStart() + totalDistance) % totalDistance; + averageTimes.get(station).add((long) (distance / sprintingSpeed)); + } + + return averageTimes; } public boolean addDetection(Detection e) { @@ -44,9 +56,12 @@ public boolean addDetection(Detection e) { currentStation = idToStation.get(e.getStationId()); if (isNextStation()) { // Only add the time if it goes forward by exactly one station - averageTimes.get(previousStation).add(System.currentTimeMillis() - previousStationArrival); + if (averageTimes.containsKey(previousStation)) { + // While only be false for the first time an interval in ran as previousStation is still null + averageTimes.get(previousStation).add(System.currentTimeMillis() / 1000 - previousStationArrival); + } } - previousStationArrival = System.currentTimeMillis(); + previousStationArrival = System.currentTimeMillis() / 1000; } return newStation; @@ -60,8 +75,8 @@ private boolean isNextStation() { public void updatePosition() { double progress = currentStation.getDistanceFromStart() / totalDistance; Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); - double distance = (nextStation.getDistanceFromStart() - currentStation.getDistanceFromStart() + totalDistance) % totalDistance; - double speed = ((distance / totalDistance) - progress) / getAverage(); // Progress / second +// double distance = (nextStation.getDistanceFromStart() - currentStation.getDistanceFromStart() + totalDistance) % totalDistance; + double speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getAverage(); // Progress / second position.update(progress, speed); } From b540279f1e8fb4a5b3d6fd393f4dfed107de3083 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 13 Apr 2024 18:39:13 +0200 Subject: [PATCH 62/90] chore: infite speed fix --- .../positioner/nostradamus/TeamData.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 03c554e..ee2044c 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -51,7 +51,7 @@ private Map> getAverageTimes(int averageAmount, double sprin public boolean addDetection(Detection e) { boolean newStation = detections.add(e); - if (newStation) { + if ((newStation && isForwardStation()) || currentStation.getId() == -10) { previousStation = currentStation; currentStation = idToStation.get(e.getStationId()); if (isNextStation()) { @@ -67,8 +67,16 @@ public boolean addDetection(Detection e) { return newStation; } + private int getStationDiff() { + return (stations.indexOf(currentStation) - stations.indexOf(previousStation) + stations.size()) % stations.size(); + } + + private boolean isForwardStation() { + return getStationDiff() > 0; + } + private boolean isNextStation() { - return (stations.indexOf(currentStation) - stations.indexOf(previousStation) + stations.size()) % stations.size() == 1; + return getStationDiff() == 1; } // TODO: Smoothen out @@ -77,11 +85,17 @@ public void updatePosition() { Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); // double distance = (nextStation.getDistanceFromStart() - currentStation.getDistanceFromStart() + totalDistance) % totalDistance; double speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getAverage(); // Progress / second +// if (Double.isInfinite(speed)) { +// System.out.println("aiaiaia"); +// System.out.println("Averages"); +// averageTimes.get(currentStation).forEach(time -> System.out.println("Time: " + time)); +// System.out.println("Average: " + getAverage()); +// } position.update(progress, speed); } private double getAverage() { - return averageTimes.get(currentStation).stream().mapToDouble(time -> time).average().orElse(0.1); + return averageTimes.get(currentStation).stream().mapToDouble(time -> time).average().getAsDouble(); } } From 52fad65af86003395c8d282c2508188b270894dc Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sun, 14 Apr 2024 15:10:42 +0200 Subject: [PATCH 63/90] fix math --- .../telraam/logic/positioner/Position.java | 12 ++++----- .../positioner/nostradamus/TeamData.java | 26 ++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 8a10da9..e9d858f 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -1,27 +1,27 @@ package telraam.logic.positioner; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.Getter; import lombok.Setter; -import java.sql.Timestamp; - -@Getter @Setter +@Getter @Setter @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class Position { private int teamId; private double progress; // Progress of the lap. Between 0-1 private double speed; // Current speed. progress / second - private long unix; + private long timestamp; public Position(int teamId) { this.teamId = teamId; this.progress = 0; this.speed = 0; - this.unix = 0; + this.timestamp = 0; } public void update(double progress, double speed) { this.progress = progress; this.speed = speed; - this.unix = System.currentTimeMillis() / 1000L;; + this.timestamp = System.currentTimeMillis() / 1000L;; } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index ee2044c..0fe5a67 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -28,7 +28,7 @@ public TeamData(int teamId, int interval, List stations, int averageAmo this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); // this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); this.previousStationArrival = System.currentTimeMillis(); - this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station + this.currentStation = new Station(-1); // Will never trigger `isNextStation` for the first station this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start this.position = new Position(teamId); this.averageTimes = getAverageTimes(averageAmount, sprintingSpeed); @@ -51,7 +51,7 @@ private Map> getAverageTimes(int averageAmount, double sprin public boolean addDetection(Detection e) { boolean newStation = detections.add(e); - if ((newStation && isForwardStation()) || currentStation.getId() == -10) { + if ((newStation && isForwardStation(currentStation, idToStation.get(e.getStationId()))) || currentStation.getId() == -1) { previousStation = currentStation; currentStation = idToStation.get(e.getStationId()); if (isNextStation()) { @@ -62,35 +62,31 @@ public boolean addDetection(Detection e) { } } previousStationArrival = System.currentTimeMillis() / 1000; + + return true; } - return newStation; + return false; } - private int getStationDiff() { - return (stations.indexOf(currentStation) - stations.indexOf(previousStation) + stations.size()) % stations.size(); + private int getStationDiff(Station oldStation, Station newStation) { + return (stations.indexOf(newStation) - stations.indexOf(oldStation) + stations.size()) % stations.size(); } - private boolean isForwardStation() { - return getStationDiff() > 0; + private boolean isForwardStation(Station oldStation, Station newStation) { + int stationDiff = getStationDiff(oldStation, newStation); + return stationDiff > 0 && stationDiff < 3; } private boolean isNextStation() { - return getStationDiff() == 1; + return getStationDiff(previousStation, currentStation) == 1; } // TODO: Smoothen out public void updatePosition() { double progress = currentStation.getDistanceFromStart() / totalDistance; Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); -// double distance = (nextStation.getDistanceFromStart() - currentStation.getDistanceFromStart() + totalDistance) % totalDistance; double speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getAverage(); // Progress / second -// if (Double.isInfinite(speed)) { -// System.out.println("aiaiaia"); -// System.out.println("Averages"); -// averageTimes.get(currentStation).forEach(time -> System.out.println("Time: " + time)); -// System.out.println("Average: " + getAverage()); -// } position.update(progress, speed); } From 1f8088ae027942acd05819ad1ee3b209dfbf2f88 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 19 Apr 2024 00:50:40 +0200 Subject: [PATCH 64/90] Smooth out animations --- .../telraam/logic/positioner/Position.java | 6 +- .../positioner/nostradamus/Nostradamus.java | 2 +- .../positioner/nostradamus/PositionList.java | 4 -- .../positioner/nostradamus/TeamData.java | 56 ++++++++++++++----- 4 files changed, 45 insertions(+), 23 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index e9d858f..6582deb 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -7,10 +7,10 @@ @Getter @Setter @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class Position { - private int teamId; + private final int teamId; private double progress; // Progress of the lap. Between 0-1 private double speed; // Current speed. progress / second - private long timestamp; + private double timestamp; public Position(int teamId) { this.teamId = teamId; @@ -22,6 +22,6 @@ public Position(int teamId) { public void update(double progress, double speed) { this.progress = progress; this.speed = speed; - this.timestamp = System.currentTimeMillis() / 1000L;; + this.timestamp = System.currentTimeMillis() / 1000D; } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 0e1230c..22831f9 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -19,7 +19,7 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching all stations, teams, ... - private final int INTERVAL_DETECTIONS_MS = 1000; // Amount of seconds to group detections by + private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals private final double AVERAGE_SPRINTING_SPEED_M_S = 6.84; // Average sprinting speed m / s private final int MIN_RSSI = -84; diff --git a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java index 7be0fa8..c4aaffb 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java @@ -24,10 +24,6 @@ public PositionList(int interval, List stations) { this.newestDetection = new Timestamp(0); } - /** - * @param e element to add - * @return True if the current position has changed - */ @Override public boolean add(Detection e) { super.add(e); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 0fe5a67..024a426 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -12,8 +12,8 @@ public class TeamData { private final PositionList detections; private final List stations; // Station list, ordered by distance from start private final Map idToStation; // Map going from a station id to the station - private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. - private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times + private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. + private Double previousStationArrival; // Arrival time of previous station. Used to calculate the average times private Station currentStation; // Current station location private Station previousStation; // Previous station location private final Double totalDistance; @@ -27,22 +27,22 @@ public TeamData(int teamId, int interval, List stations, int averageAmo this.detections = new PositionList(interval, this.stations); this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); // this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); - this.previousStationArrival = System.currentTimeMillis(); - this.currentStation = new Station(-1); // Will never trigger `isNextStation` for the first station + this.previousStationArrival = System.currentTimeMillis() / 1000D; + this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start - this.position = new Position(teamId); this.averageTimes = getAverageTimes(averageAmount, sprintingSpeed); + this.position = new Position(teamId); } // Construct the average times and add a default value // TODO: Populate with existing detections - private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { - Map> averageTimes = new HashMap<>(); + private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { + Map> averageTimes = new HashMap<>(); for (Station station: stations) { int index = stations.indexOf(station); averageTimes.put(station, new CircularQueue<>(averageAmount)); double distance = (stations.get((index + 1) % stations.size()).getDistanceFromStart() - station.getDistanceFromStart() + totalDistance) % totalDistance; - averageTimes.get(station).add((long) (distance / sprintingSpeed)); + averageTimes.get(station).add((distance / sprintingSpeed)); } return averageTimes; @@ -58,10 +58,11 @@ public boolean addDetection(Detection e) { // Only add the time if it goes forward by exactly one station if (averageTimes.containsKey(previousStation)) { // While only be false for the first time an interval in ran as previousStation is still null - averageTimes.get(previousStation).add(System.currentTimeMillis() / 1000 - previousStationArrival); + averageTimes.get(previousStation).add(System.currentTimeMillis() / 1000D - previousStationArrival); } } - previousStationArrival = System.currentTimeMillis() / 1000; + + previousStationArrival = System.currentTimeMillis() / 1000D; return true; } @@ -82,16 +83,41 @@ private boolean isNextStation() { return getStationDiff(previousStation, currentStation) == 1; } - // TODO: Smoothen out public void updatePosition() { - double progress = currentStation.getDistanceFromStart() / totalDistance; + // Arrive at second x + double currentTime = System.currentTimeMillis() / 1000D; + double nextStationArrival = currentTime + getMedian(); + + // Current at progress y + double secondsSince = currentTime - position.getTimestamp(); + double theoreticalProgress = (position.getProgress() + (position.getSpeed() * secondsSince)) % 1; + + // Progress in z amount of seconds Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); - double speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getAverage(); // Progress / second + double goalProgress = nextStation.getDistanceFromStart() / totalDistance; + double speed, progress; + // TODO: Do in a different way + // TODO: Right now assumes the difference between each station is the same + if ((goalProgress - theoreticalProgress + 1) % 1 >= 1 - ((double) 1 / stations.size()) || averageTimes.get(currentStation).size() < 5) { + // Animation was already further than the next station so just tp + progress = currentStation.getDistanceFromStart() / totalDistance; + speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getMedian(); + } else { + // Animation is either behind or maximum in front by one station. Adjust so we're synced at the next station + progress = theoreticalProgress; + speed = ((goalProgress - theoreticalProgress + 1) % 1) / (nextStationArrival - currentTime); + } position.update(progress, speed); } - private double getAverage() { - return averageTimes.get(currentStation).stream().mapToDouble(time -> time).average().getAsDouble(); + private double getMedian() { + List sortedList = new ArrayList<>(averageTimes.get(currentStation)); + Collections.sort(sortedList); + + int size = sortedList.size(); + return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2D : sortedList.get(size / 2); } } + +// TODO: Possible problem: Might arrive to early at station -> Move backwards stations by 5 m From ab0b0cb3807967793c7113e18602a628c60d43d6 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 19 Apr 2024 14:48:51 +0200 Subject: [PATCH 65/90] chore: seconds to milliseconds --- .../telraam/logic/positioner/Position.java | 4 +-- .../positioner/nostradamus/Nostradamus.java | 4 +-- .../positioner/nostradamus/TeamData.java | 28 +++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 6582deb..1a0e002 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -10,7 +10,7 @@ public class Position { private final int teamId; private double progress; // Progress of the lap. Between 0-1 private double speed; // Current speed. progress / second - private double timestamp; + private long timestamp; public Position(int teamId) { this.teamId = teamId; @@ -22,6 +22,6 @@ public Position(int teamId) { public void update(double progress, double speed) { this.progress = progress; this.speed = speed; - this.timestamp = System.currentTimeMillis() / 1000D; + this.timestamp = System.currentTimeMillis(); } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 22831f9..3e91aba 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -21,7 +21,7 @@ public class Nostradamus implements Positioner { private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching all stations, teams, ... private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals - private final double AVERAGE_SPRINTING_SPEED_M_S = 6.84; // Average sprinting speed m / s + private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed m / ms private final int MIN_RSSI = -84; private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections @@ -53,7 +53,7 @@ private void setTeamData() { teamData = teams.stream().collect(Collectors.toMap( Team::getId, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_S) + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS) )); } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 024a426..cec2948 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -12,8 +12,8 @@ public class TeamData { private final PositionList detections; private final List stations; // Station list, ordered by distance from start private final Map idToStation; // Map going from a station id to the station - private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. - private Double previousStationArrival; // Arrival time of previous station. Used to calculate the average times + private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. + private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private Station currentStation; // Current station location private Station previousStation; // Previous station location private final Double totalDistance; @@ -27,7 +27,7 @@ public TeamData(int teamId, int interval, List stations, int averageAmo this.detections = new PositionList(interval, this.stations); this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); // this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); - this.previousStationArrival = System.currentTimeMillis() / 1000D; + this.previousStationArrival = System.currentTimeMillis(); this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start this.averageTimes = getAverageTimes(averageAmount, sprintingSpeed); @@ -36,13 +36,13 @@ public TeamData(int teamId, int interval, List stations, int averageAmo // Construct the average times and add a default value // TODO: Populate with existing detections - private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { - Map> averageTimes = new HashMap<>(); + private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { + Map> averageTimes = new HashMap<>(); for (Station station: stations) { int index = stations.indexOf(station); averageTimes.put(station, new CircularQueue<>(averageAmount)); double distance = (stations.get((index + 1) % stations.size()).getDistanceFromStart() - station.getDistanceFromStart() + totalDistance) % totalDistance; - averageTimes.get(station).add((distance / sprintingSpeed)); + averageTimes.get(station).add((long) (distance / sprintingSpeed)); } return averageTimes; @@ -58,11 +58,11 @@ public boolean addDetection(Detection e) { // Only add the time if it goes forward by exactly one station if (averageTimes.containsKey(previousStation)) { // While only be false for the first time an interval in ran as previousStation is still null - averageTimes.get(previousStation).add(System.currentTimeMillis() / 1000D - previousStationArrival); + averageTimes.get(previousStation).add(System.currentTimeMillis() - previousStationArrival); } } - previousStationArrival = System.currentTimeMillis() / 1000D; + previousStationArrival = System.currentTimeMillis(); return true; } @@ -84,13 +84,13 @@ private boolean isNextStation() { } public void updatePosition() { - // Arrive at second x - double currentTime = System.currentTimeMillis() / 1000D; + // Arrive at millisecond x + double currentTime = System.currentTimeMillis(); double nextStationArrival = currentTime + getMedian(); // Current at progress y - double secondsSince = currentTime - position.getTimestamp(); - double theoreticalProgress = (position.getProgress() + (position.getSpeed() * secondsSince)) % 1; + double milliSecondsSince = currentTime - position.getTimestamp(); + double theoreticalProgress = (position.getProgress() + (position.getSpeed() * milliSecondsSince)) % 1; // Progress in z amount of seconds Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); @@ -112,11 +112,11 @@ public void updatePosition() { } private double getMedian() { - List sortedList = new ArrayList<>(averageTimes.get(currentStation)); + List sortedList = new ArrayList<>(averageTimes.get(currentStation)); Collections.sort(sortedList); int size = sortedList.size(); - return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2D : sortedList.get(size / 2); + return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2D : (sortedList.get(size / 2)); } } From 05eb54f8243ce7263bff7890a606bb6449a710f4 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 19 Apr 2024 18:21:24 +0200 Subject: [PATCH 66/90] Refactor: Group common data --- .../positioner/nostradamus/Nostradamus.java | 4 +- .../positioner/nostradamus/PositionList.java | 1 + .../positioner/nostradamus/StationData.java | 25 ++++ .../positioner/nostradamus/TeamData.java | 123 ++++++++---------- 4 files changed, 86 insertions(+), 67 deletions(-) create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/StationData.java diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 3e91aba..8f5004d 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -23,6 +23,7 @@ public class Nostradamus implements Positioner { private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed m / ms private final int MIN_RSSI = -84; + private final int FINISH_OFFSET = 0; private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections private final Lock detectionLock; @@ -49,11 +50,12 @@ public Nostradamus(Jdbi jdbi) { private void setTeamData() { List stations = jdbi.onDemand(StationDAO.class).getAll(); + stations.sort(Comparator.comparing(Station::getDistanceFromStart)); List teams = jdbi.onDemand(TeamDAO.class).getAll(); teamData = teams.stream().collect(Collectors.toMap( Team::getId, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS) + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET) )); } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java index c4aaffb..e1c8944 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java @@ -24,6 +24,7 @@ public PositionList(int interval, List stations) { this.newestDetection = new Timestamp(0); } + // Returns True if it's a new station @Override public boolean add(Detection e) { super.add(e); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java new file mode 100644 index 0000000..e65101d --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java @@ -0,0 +1,25 @@ +package telraam.logic.positioner.nostradamus; + +import telraam.database.models.Station; + +import java.util.List; + +public record StationData( + Station station, // The station + Station nextStation, // The next station + List averageTimes, // List containing the times (in ms) that was needed to run from this station to the next one. + int index, // Index of this station when sorting a station list by distanceFromStart + double currentProgress, // The progress value of this station + double nextProgress // The progress value of the next station +) { + public StationData(List stations, int index, int averageAmount, int totalDistance) { + this( + stations.get(index), + stations.get((index + 1) % stations.size()), + new CircularQueue<>(averageAmount), + index, + stations.get(index).getDistanceFromStart() / totalDistance, + stations.get((index + 1) % stations.size()).getDistanceFromStart() / totalDistance + ); + } +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index cec2948..ba5f047 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -9,59 +9,53 @@ import java.util.stream.Collectors; public class TeamData { - private final PositionList detections; - private final List stations; // Station list, ordered by distance from start - private final Map idToStation; // Map going from a station id to the station - private final Map> averageTimes; // List of average times for each station. Going from station 2 to 3 is saved in 3. + private final PositionList detections; // List with all relevant detections + private final Map stations; // Station list private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times - private Station currentStation; // Current station location - private Station previousStation; // Previous station location - private final Double totalDistance; + private StationData currentStation; // Current station location + private StationData previousStation; // Previous station location + private final int totalDistance; // Total distance of the track @Getter - private final Position position; - - - public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed) { - this.stations = stations; - this.stations.sort(Comparator.comparing(Station::getDistanceFromStart)); - this.detections = new PositionList(interval, this.stations); - this.idToStation = stations.stream().collect(Collectors.toMap(Station::getId, station -> station)); -// this.averageTimes = stations.stream().collect(Collectors.toMap(station -> station, station -> new CircularQueue<>(averageAmount))); + private final Position position; // Data to send to the websocket + private final int maxDeviance; // Maximum deviance the animation can have from the reality + + + public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { + stations.sort(Comparator.comparing(Station::getDistanceFromStart)); + this.totalDistance = (int) (stations.get(stations.size() - 1).getDistanceFromStart() + finishOffset); + this.stations = stations.stream().collect(Collectors.toMap( + Station::getId, + station -> new StationData( + stations, + stations.indexOf(station), + averageAmount, + totalDistance + ) + )); + // Pre-populate with some data + this.stations.forEach((stationId, stationData) -> stationData.averageTimes().add( + (long) (((stationData.nextStation().getDistanceFromStart() - stationData.station().getDistanceFromStart() + totalDistance) % totalDistance) / sprintingSpeed) + )); + this.detections = new PositionList(interval, stations); this.previousStationArrival = System.currentTimeMillis(); - this.currentStation = new Station(-10); // Will never trigger `isNextStation` for the first station - this.totalDistance = this.stations.get(this.stations.size() - 1).getDistanceFromStart(); // Requires last station to be located at the start - this.averageTimes = getAverageTimes(averageAmount, sprintingSpeed); + this.currentStation = new StationData(new Station(-10), new Station(-9), new CircularQueue<>(0), -10, -10, -10); // Will never trigger `isNextStation` for the first station this.position = new Position(teamId); + this.maxDeviance = 1 / stations.size(); } - // Construct the average times and add a default value - // TODO: Populate with existing detections - private Map> getAverageTimes(int averageAmount, double sprintingSpeed) { - Map> averageTimes = new HashMap<>(); - for (Station station: stations) { - int index = stations.indexOf(station); - averageTimes.put(station, new CircularQueue<>(averageAmount)); - double distance = (stations.get((index + 1) % stations.size()).getDistanceFromStart() - station.getDistanceFromStart() + totalDistance) % totalDistance; - averageTimes.get(station).add((long) (distance / sprintingSpeed)); - } - - return averageTimes; - } - + // Add a new detection + // Returns true if the team is at a next station public boolean addDetection(Detection e) { boolean newStation = detections.add(e); - if ((newStation && isForwardStation(currentStation, idToStation.get(e.getStationId()))) || currentStation.getId() == -1) { + if ((newStation && isForwardStation(currentStation.index(), stations.get(e.getStationId()).index())) || currentStation.index() == -10) { + // Is at a new station that is in front of the previous one. previousStation = currentStation; - currentStation = idToStation.get(e.getStationId()); + currentStation = stations.get(e.getStationId()); if (isNextStation()) { // Only add the time if it goes forward by exactly one station - if (averageTimes.containsKey(previousStation)) { - // While only be false for the first time an interval in ran as previousStation is still null - averageTimes.get(previousStation).add(System.currentTimeMillis() - previousStationArrival); - } + previousStation.averageTimes().add(System.currentTimeMillis() - previousStationArrival); } - previousStationArrival = System.currentTimeMillis(); return true; @@ -70,40 +64,36 @@ public boolean addDetection(Detection e) { return false; } - private int getStationDiff(Station oldStation, Station newStation) { - return (stations.indexOf(newStation) - stations.indexOf(oldStation) + stations.size()) % stations.size(); - } - - private boolean isForwardStation(Station oldStation, Station newStation) { - int stationDiff = getStationDiff(oldStation, newStation); + private boolean isForwardStation(int oldStation, int newStation) { + int stationDiff = (newStation - oldStation + stations.size()) % stations.size(); return stationDiff > 0 && stationDiff < 3; } private boolean isNextStation() { - return getStationDiff(previousStation, currentStation) == 1; + return Objects.equals(previousStation.nextStation().getId(), currentStation.station().getId()); } + // Update the position data public void updatePosition() { - // Arrive at millisecond x - double currentTime = System.currentTimeMillis(); - double nextStationArrival = currentTime + getMedian(); + long currentTime = System.currentTimeMillis(); - // Current at progress y - double milliSecondsSince = currentTime - position.getTimestamp(); + // Animation is currently at progress x + long milliSecondsSince = currentTime - position.getTimestamp(); double theoreticalProgress = (position.getProgress() + (position.getSpeed() * milliSecondsSince)) % 1; - // Progress in z amount of seconds - Station nextStation = stations.get((stations.indexOf(currentStation) + 1) % stations.size()); - double goalProgress = nextStation.getDistanceFromStart() / totalDistance; + // Arrive at next station at timestamp y and progress z + long nextStationArrival = currentTime + getMedian(); + double goalProgress = currentStation.nextProgress(); + double speed, progress; - // TODO: Do in a different way - // TODO: Right now assumes the difference between each station is the same - if ((goalProgress - theoreticalProgress + 1) % 1 >= 1 - ((double) 1 / stations.size()) || averageTimes.get(currentStation).size() < 5) { - // Animation was already further than the next station so just tp - progress = currentStation.getDistanceFromStart() / totalDistance; - speed = (((nextStation.getDistanceFromStart() / totalDistance) - progress + 1) % 1) / getMedian(); + // Determine whether to speed up / slow down the animation or teleport it + double difference = (goalProgress - theoreticalProgress + 1) % 1; + if ((difference >= maxDeviance && difference <= 1 - maxDeviance) || previousStation.averageTimes().size() < 5) { + // Animation was too far behind or ahead so teleport + progress = currentStation.currentProgress(); + speed = ((currentStation.nextProgress() - progress + 1) % 1) / getMedian(); } else { - // Animation is either behind or maximum in front by one station. Adjust so we're synced at the next station + // Animation is close enough, adjust so that we're synced at the next station progress = theoreticalProgress; speed = ((goalProgress - theoreticalProgress + 1) % 1) / (nextStationArrival - currentTime); } @@ -111,13 +101,14 @@ public void updatePosition() { position.update(progress, speed); } - private double getMedian() { - List sortedList = new ArrayList<>(averageTimes.get(currentStation)); + // Get the medium of the average times + private long getMedian() { + List sortedList = new ArrayList<>(currentStation.averageTimes()); Collections.sort(sortedList); int size = sortedList.size(); - return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2D : (sortedList.get(size / 2)); + return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2 : (sortedList.get(size / 2)); } } -// TODO: Possible problem: Might arrive to early at station -> Move backwards stations by 5 m +// TODO: Possible problem: Might arrive to early at station -> Move backwards stations by 5 meter From a762b44299e2396fb2b37d4c54960b627b5130a5 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 20 Apr 2024 00:21:20 +0200 Subject: [PATCH 67/90] chore: smoothen out some more --- .../telraam/logic/positioner/Position.java | 1 + .../positioner/nostradamus/TeamData.java | 21 +++++++++++++------ .../station/websocket/WebsocketFetcher.java | 1 - 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 1a0e002..5914a97 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -23,5 +23,6 @@ public void update(double progress, double speed) { this.progress = progress; this.speed = speed; this.timestamp = System.currentTimeMillis(); + System.out.println("Progress: " + progress + " | Speed: " + speed + " | Timestamp: " + timestamp); } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index ba5f047..cdf9830 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -17,7 +17,7 @@ public class TeamData { private final int totalDistance; // Total distance of the track @Getter private final Position position; // Data to send to the websocket - private final int maxDeviance; // Maximum deviance the animation can have from the reality + private final double maxDeviance; // Maximum deviance the animation can have from the reality public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { @@ -40,7 +40,7 @@ public TeamData(int teamId, int interval, List stations, int averageAmo this.previousStationArrival = System.currentTimeMillis(); this.currentStation = new StationData(new Station(-10), new Station(-9), new CircularQueue<>(0), -10, -10, -10); // Will never trigger `isNextStation` for the first station this.position = new Position(teamId); - this.maxDeviance = 1 / stations.size(); + this.maxDeviance = (double) 1 / stations.size(); } // Add a new detection @@ -52,11 +52,13 @@ public boolean addDetection(Detection e) { // Is at a new station that is in front of the previous one. previousStation = currentStation; currentStation = stations.get(e.getStationId()); + System.out.println("Station: " + currentStation.index()); + long now = System.currentTimeMillis(); if (isNextStation()) { // Only add the time if it goes forward by exactly one station - previousStation.averageTimes().add(System.currentTimeMillis() - previousStationArrival); + previousStation.averageTimes().add(now - previousStationArrival); } - previousStationArrival = System.currentTimeMillis(); + previousStationArrival = now; return true; } @@ -87,13 +89,20 @@ public void updatePosition() { double speed, progress; // Determine whether to speed up / slow down the animation or teleport it - double difference = (goalProgress - theoreticalProgress + 1) % 1; - if ((difference >= maxDeviance && difference <= 1 - maxDeviance) || previousStation.averageTimes().size() < 5) { + double difference = (currentStation.currentProgress() - theoreticalProgress + 1) % 1; + if ((difference >= maxDeviance && difference <= 1 - maxDeviance) || currentStation.averageTimes().size() < 3) { + System.out.println("Too fast"); + System.out.println("Size: " + currentStation.averageTimes().size()); + System.out.print("Average times: "); + currentStation.averageTimes().forEach(time -> System.out.print(" | " + time)); + System.out.println(""); + System.out.println("Goal: " + currentStation.currentProgress() + " Theoretical: " + theoreticalProgress + " Difference: " + (currentStation.currentProgress() - theoreticalProgress + 1) % 1); // Animation was too far behind or ahead so teleport progress = currentStation.currentProgress(); speed = ((currentStation.nextProgress() - progress + 1) % 1) / getMedian(); } else { // Animation is close enough, adjust so that we're synced at the next station + System.out.println("Good"); progress = theoreticalProgress; speed = ((goalProgress - theoreticalProgress + 1) % 1) / (nextStationArrival - currentTime); } diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java index 24c78b4..62e9996 100644 --- a/src/main/java/telraam/station/websocket/WebsocketFetcher.java +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -90,7 +90,6 @@ public void fetch() { return; } - WebsocketClient websocketClient = new WebsocketClient(url); websocketClient.addOnOpenHandler(() -> { websocketClient.sendMessage(wsMessageEncoded); From ec495ea6846d1b4f212b17007308947f3d775d55 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 20 Apr 2024 14:23:19 +0200 Subject: [PATCH 68/90] chore; remove prints statements --- src/main/java/telraam/logic/positioner/Position.java | 1 - .../telraam/logic/positioner/nostradamus/TeamData.java | 8 -------- 2 files changed, 9 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 5914a97..1a0e002 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -23,6 +23,5 @@ public void update(double progress, double speed) { this.progress = progress; this.speed = speed; this.timestamp = System.currentTimeMillis(); - System.out.println("Progress: " + progress + " | Speed: " + speed + " | Timestamp: " + timestamp); } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index cdf9830..c173ea8 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -52,7 +52,6 @@ public boolean addDetection(Detection e) { // Is at a new station that is in front of the previous one. previousStation = currentStation; currentStation = stations.get(e.getStationId()); - System.out.println("Station: " + currentStation.index()); long now = System.currentTimeMillis(); if (isNextStation()) { // Only add the time if it goes forward by exactly one station @@ -91,18 +90,11 @@ public void updatePosition() { // Determine whether to speed up / slow down the animation or teleport it double difference = (currentStation.currentProgress() - theoreticalProgress + 1) % 1; if ((difference >= maxDeviance && difference <= 1 - maxDeviance) || currentStation.averageTimes().size() < 3) { - System.out.println("Too fast"); - System.out.println("Size: " + currentStation.averageTimes().size()); - System.out.print("Average times: "); - currentStation.averageTimes().forEach(time -> System.out.print(" | " + time)); - System.out.println(""); - System.out.println("Goal: " + currentStation.currentProgress() + " Theoretical: " + theoreticalProgress + " Difference: " + (currentStation.currentProgress() - theoreticalProgress + 1) % 1); // Animation was too far behind or ahead so teleport progress = currentStation.currentProgress(); speed = ((currentStation.nextProgress() - progress + 1) % 1) / getMedian(); } else { // Animation is close enough, adjust so that we're synced at the next station - System.out.println("Good"); progress = theoreticalProgress; speed = ((goalProgress - theoreticalProgress + 1) % 1) / (nextStationArrival - currentTime); } From 78f1ea511797967352f8773eef40c1ce54213fb3 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 20 Apr 2024 15:54:49 +0200 Subject: [PATCH 69/90] chore: sync up faster --- src/main/java/telraam/api/TeamResource.java | 3 -- .../{PositionList.java => DetectionList.java} | 4 +-- .../positioner/nostradamus/Nostradamus.java | 6 ++-- .../positioner/nostradamus/StationData.java | 22 ++++++++++--- .../positioner/nostradamus/TeamData.java | 31 +++++++++---------- 5 files changed, 38 insertions(+), 28 deletions(-) rename src/main/java/telraam/logic/positioner/nostradamus/{PositionList.java => DetectionList.java} (94%) diff --git a/src/main/java/telraam/api/TeamResource.java b/src/main/java/telraam/api/TeamResource.java index 5983eff..9bf36c3 100644 --- a/src/main/java/telraam/api/TeamResource.java +++ b/src/main/java/telraam/api/TeamResource.java @@ -51,9 +51,6 @@ public Team update(Team team, Optional id) { Team previousTeam = this.get(id); Team ret = super.update(team, id); - System.out.println(previousTeam.getBatonId()); - System.out.println(team.getBatonId()); - if (!Objects.equals(previousTeam.getBatonId(), team.getBatonId())) { this.batonSwitchoverDAO.insert(new BatonSwitchover( team.getId(), diff --git a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java b/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java similarity index 94% rename from src/main/java/telraam/logic/positioner/nostradamus/PositionList.java rename to src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java index e1c8944..4e128a2 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/PositionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java @@ -9,7 +9,7 @@ import java.util.Comparator; import java.util.List; -public class PositionList extends ArrayList { +public class DetectionList extends ArrayList { private final int interval; private final List stations; @@ -17,7 +17,7 @@ public class PositionList extends ArrayList { private Detection currentPosition; private Timestamp newestDetection; - public PositionList(int interval, List stations) { + public DetectionList(int interval, List stations) { this.interval = interval; this.stations = stations.stream().sorted(Comparator.comparing(Station::getDistanceFromStart)).map(Station::getId).toList(); this.currentPosition = new Detection(-1, 0, -100); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 8f5004d..f2a2669 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -1,11 +1,13 @@ package telraam.logic.positioner.nostradamus; import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonDAO; import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.daos.StationDAO; import telraam.database.daos.TeamDAO; -import telraam.database.models.*; +import telraam.database.models.BatonSwitchover; +import telraam.database.models.Detection; +import telraam.database.models.Station; +import telraam.database.models.Team; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; diff --git a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java index e65101d..c3b3537 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java @@ -2,24 +2,36 @@ import telraam.database.models.Station; +import java.util.ArrayList; import java.util.List; public record StationData( Station station, // The station Station nextStation, // The next station - List averageTimes, // List containing the times (in ms) that was needed to run from this station to the next one. + List times, // List containing the times (in ms) that was needed to run from this station to the next one. int index, // Index of this station when sorting a station list by distanceFromStart - double currentProgress, // The progress value of this station - double nextProgress // The progress value of the next station + float currentProgress, // The progress value of this station + float nextProgress // The progress value of the next station ) { + public StationData() { + this( + new Station(-10), + new Station(-9), + new ArrayList<>(0), + -10, + 0F, + 0F + ); + } + public StationData(List stations, int index, int averageAmount, int totalDistance) { this( stations.get(index), stations.get((index + 1) % stations.size()), new CircularQueue<>(averageAmount), index, - stations.get(index).getDistanceFromStart() / totalDistance, - stations.get((index + 1) % stations.size()).getDistanceFromStart() / totalDistance + (float) (stations.get(index).getDistanceFromStart() / totalDistance), + (float) (stations.get((index + 1) % stations.size()).getDistanceFromStart() / totalDistance) ); } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index c173ea8..df2e844 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -9,7 +9,7 @@ import java.util.stream.Collectors; public class TeamData { - private final PositionList detections; // List with all relevant detections + private final DetectionList detections; // List with all relevant detections private final Map stations; // Station list private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private StationData currentStation; // Current station location @@ -17,7 +17,7 @@ public class TeamData { private final int totalDistance; // Total distance of the track @Getter private final Position position; // Data to send to the websocket - private final double maxDeviance; // Maximum deviance the animation can have from the reality + private final float maxDeviance; // Maximum deviance the animation can have from the reality public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { @@ -33,18 +33,18 @@ public TeamData(int teamId, int interval, List stations, int averageAmo ) )); // Pre-populate with some data - this.stations.forEach((stationId, stationData) -> stationData.averageTimes().add( + this.stations.forEach((stationId, stationData) -> stationData.times().add( (long) (((stationData.nextStation().getDistanceFromStart() - stationData.station().getDistanceFromStart() + totalDistance) % totalDistance) / sprintingSpeed) )); - this.detections = new PositionList(interval, stations); + this.detections = new DetectionList(interval, stations); this.previousStationArrival = System.currentTimeMillis(); - this.currentStation = new StationData(new Station(-10), new Station(-9), new CircularQueue<>(0), -10, -10, -10); // Will never trigger `isNextStation` for the first station + this.currentStation = new StationData(); // Will never trigger `isNextStation` for the first station this.position = new Position(teamId); - this.maxDeviance = (double) 1 / stations.size(); + this.maxDeviance = (float) 1 / stations.size(); } // Add a new detection - // Returns true if the team is at a next station + // Returns true if the team is at a new station public boolean addDetection(Detection e) { boolean newStation = detections.add(e); @@ -55,7 +55,7 @@ public boolean addDetection(Detection e) { long now = System.currentTimeMillis(); if (isNextStation()) { // Only add the time if it goes forward by exactly one station - previousStation.averageTimes().add(now - previousStationArrival); + previousStation.times().add(now - previousStationArrival); } previousStationArrival = now; @@ -67,7 +67,7 @@ public boolean addDetection(Detection e) { private boolean isForwardStation(int oldStation, int newStation) { int stationDiff = (newStation - oldStation + stations.size()) % stations.size(); - return stationDiff > 0 && stationDiff < 3; + return stationDiff < 3; } private boolean isNextStation() { @@ -83,16 +83,17 @@ public void updatePosition() { double theoreticalProgress = (position.getProgress() + (position.getSpeed() * milliSecondsSince)) % 1; // Arrive at next station at timestamp y and progress z - long nextStationArrival = currentTime + getMedian(); + double median = getMedian(currentStation.times()); + double nextStationArrival = currentTime + median; double goalProgress = currentStation.nextProgress(); double speed, progress; // Determine whether to speed up / slow down the animation or teleport it double difference = (currentStation.currentProgress() - theoreticalProgress + 1) % 1; - if ((difference >= maxDeviance && difference <= 1 - maxDeviance) || currentStation.averageTimes().size() < 3) { + if ((difference >= maxDeviance && difference <= 1 - maxDeviance)) { // Animation was too far behind or ahead so teleport progress = currentStation.currentProgress(); - speed = ((currentStation.nextProgress() - progress + 1) % 1) / getMedian(); + speed = ((currentStation.nextProgress() - progress + 1) % 1) / median; } else { // Animation is close enough, adjust so that we're synced at the next station progress = theoreticalProgress; @@ -103,13 +104,11 @@ public void updatePosition() { } // Get the medium of the average times - private long getMedian() { - List sortedList = new ArrayList<>(currentStation.averageTimes()); + private long getMedian(List times) { + List sortedList = new ArrayList<>(times); Collections.sort(sortedList); int size = sortedList.size(); return size % 2 == 0 ? (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2 : (sortedList.get(size / 2)); } } - -// TODO: Possible problem: Might arrive to early at station -> Move backwards stations by 5 meter From 5a882fc5033991f769c97160f73d49bde5b5ff7d Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 20 Apr 2024 20:13:55 +0200 Subject: [PATCH 70/90] chore: Send speed 0 when no data is received --- .../java/telraam/logic/positioner/Position.java | 17 ++++++++++++----- .../positioner/nostradamus/Nostradamus.java | 15 ++++++++++++++- .../logic/positioner/nostradamus/TeamData.java | 15 ++++++++++----- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 1a0e002..43f8e26 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -9,19 +9,26 @@ public class Position { private final int teamId; private double progress; // Progress of the lap. Between 0-1 - private double speed; // Current speed. progress / second - private long timestamp; + private double speed; // Current speed. progress / millisecond + private long timestamp; // Timestamp in milliseconds public Position(int teamId) { this.teamId = teamId; this.progress = 0; this.speed = 0; - this.timestamp = 0; + this.timestamp = System.currentTimeMillis(); } - public void update(double progress, double speed) { + public Position(int teamId, double progress) { + this.teamId = teamId; this.progress = progress; - this.speed = speed; + this.speed = 0; this.timestamp = System.currentTimeMillis(); } + + public void update(double progress, double speed, long timestamp) { + this.progress = progress; + this.speed = speed; + this.timestamp = timestamp; + } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index f2a2669..325368e 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -8,6 +8,7 @@ import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.database.models.Team; +import telraam.logic.positioner.Position; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; @@ -26,6 +27,7 @@ public class Nostradamus implements Positioner { private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed m / ms private final int MIN_RSSI = -84; private final int FINISH_OFFSET = 0; + private final int MAX_NO_DATA_MS = 30000; private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections private final Lock detectionLock; @@ -102,6 +104,7 @@ private void calculatePosition() { } newDetections.clear(); detectionLock.unlock(); // Use lock as short as possible + dataLock.unlock(); if (!changedTeams.isEmpty()) { // Update @@ -115,7 +118,17 @@ private void calculatePosition() { ); } - dataLock.unlock(); + long now = System.currentTimeMillis(); + for (Map.Entry entry: teamData.entrySet()) { + if (now - entry.getValue().getPreviousStationArrival() > MAX_NO_DATA_MS) { + positionSender.send( + Collections.singletonList(new Position( + entry.getKey(), + entry.getValue().getPosition().getProgress() + )) + ); + } + } // zzzzzzzz try { diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index df2e844..f98dc9b 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -11,6 +11,7 @@ public class TeamData { private final DetectionList detections; // List with all relevant detections private final Map stations; // Station list + @Getter private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private StationData currentStation; // Current station location private StationData previousStation; // Previous station location @@ -74,13 +75,17 @@ private boolean isNextStation() { return Objects.equals(previousStation.nextStation().getId(), currentStation.station().getId()); } + private double normalize(double number) { + return (number + 1) % 1; + } + // Update the position data public void updatePosition() { long currentTime = System.currentTimeMillis(); // Animation is currently at progress x long milliSecondsSince = currentTime - position.getTimestamp(); - double theoreticalProgress = (position.getProgress() + (position.getSpeed() * milliSecondsSince)) % 1; + double theoreticalProgress = normalize(position.getProgress() + (position.getSpeed() * milliSecondsSince)); // Arrive at next station at timestamp y and progress z double median = getMedian(currentStation.times()); @@ -89,18 +94,18 @@ public void updatePosition() { double speed, progress; // Determine whether to speed up / slow down the animation or teleport it - double difference = (currentStation.currentProgress() - theoreticalProgress + 1) % 1; + double difference = normalize(currentStation.currentProgress() - theoreticalProgress); if ((difference >= maxDeviance && difference <= 1 - maxDeviance)) { // Animation was too far behind or ahead so teleport progress = currentStation.currentProgress(); - speed = ((currentStation.nextProgress() - progress + 1) % 1) / median; + speed = normalize(currentStation.nextProgress() - progress) / median; } else { // Animation is close enough, adjust so that we're synced at the next station progress = theoreticalProgress; - speed = ((goalProgress - theoreticalProgress + 1) % 1) / (nextStationArrival - currentTime); + speed = normalize(goalProgress - theoreticalProgress) / (nextStationArrival - currentTime); } - position.update(progress, speed); + position.update(progress, speed, currentTime); } // Get the medium of the average times From 6803c63fc8965d316034fe4e82ca943844740e8b Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sat, 20 Apr 2024 20:33:39 +0200 Subject: [PATCH 71/90] Docs: Added comments --- .../positioner/nostradamus/CircularQueue.java | 1 + .../positioner/nostradamus/DetectionList.java | 2 +- .../positioner/nostradamus/Nostradamus.java | 38 ++++++++++--------- .../positioner/nostradamus/StationData.java | 1 + .../positioner/nostradamus/TeamData.java | 14 +++---- 5 files changed, 31 insertions(+), 25 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java b/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java index 997e9bf..1b2faae 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java @@ -2,6 +2,7 @@ import java.util.LinkedList; +// LinkedList with a maximum length public class CircularQueue extends LinkedList { private final int maxSize; diff --git a/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java b/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java index 4e128a2..30d5848 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java @@ -24,7 +24,7 @@ public DetectionList(int interval, List stations) { this.newestDetection = new Timestamp(0); } - // Returns True if it's a new station + // Returns True if the added detection results in a new station @Override public boolean add(Detection e) { super.add(e); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 325368e..4b503b3 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -20,21 +20,21 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); - private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections - private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching all stations, teams, ... + private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections (in milliseconds) + private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching baton switchovers (in milliseconds) private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by - private final int AVERAGE_AMOUNT = 10; // Calculate the average running speed the last x intervals - private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed m / ms - private final int MIN_RSSI = -84; - private final int FINISH_OFFSET = 0; - private final int MAX_NO_DATA_MS = 30000; + private final int MAX_NO_DATA_MS = 30000; // Send a stationary position after receiving no station update for x amount of milliseconds + private final int AVERAGE_AMOUNT = 10; // Calculate the median running speed of the last x intervals + private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed meters / milliseconds + private final int MIN_RSSI = -84; // Minimum rssi strength for a detection + private final int FINISH_OFFSET_M = 0; // Distance between the last station and the finish in meters private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections - private final Lock detectionLock; - private final Lock dataLock; private Map batonToTeam; // Baton ID to Team ID - private Map teamData; // All team data + private final Map teamData; // All team data private final PositionSender positionSender; + private final Lock detectionLock; + private final Lock dataLock; public Nostradamus(Jdbi jdbi) { this.jdbi = jdbi; @@ -44,7 +44,7 @@ public Nostradamus(Jdbi jdbi) { // Will be filled by fetch this.batonToTeam = new HashMap<>(); - setTeamData(); + this.teamData = getTeamData(); this.positionSender = new PositionSender(); @@ -52,17 +52,19 @@ public Nostradamus(Jdbi jdbi) { new Thread(this::calculatePosition).start(); } - private void setTeamData() { + // Initiate the team data map + private Map getTeamData() { List stations = jdbi.onDemand(StationDAO.class).getAll(); stations.sort(Comparator.comparing(Station::getDistanceFromStart)); List teams = jdbi.onDemand(TeamDAO.class).getAll(); - teamData = teams.stream().collect(Collectors.toMap( + return teams.stream().collect(Collectors.toMap( Team::getId, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET) + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET_M) )); } + // Fetch all baton switchovers and replace the current one if there are any changes private void fetch() { List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); @@ -80,7 +82,7 @@ private void fetch() { dataLock.unlock(); } - // zzzzzzzz + // Sleep tight try { Thread.sleep(INTERVAL_FETCH_MS); } catch (InterruptedException e) { @@ -88,11 +90,12 @@ private void fetch() { } } + // handle all new detections and update positions accordingly private void calculatePosition() { Set changedTeams = new HashSet<>(); // List of teams that have changed station while (true) { - dataLock.lock(); changedTeams.clear(); + dataLock.lock(); detectionLock.lock(); for (Detection detection: newDetections) { if (batonToTeam.containsKey(detection.getBatonId())) { @@ -118,6 +121,7 @@ private void calculatePosition() { ); } + // Send a stationary position if no new station data was received recently long now = System.currentTimeMillis(); for (Map.Entry entry: teamData.entrySet()) { if (now - entry.getValue().getPreviousStationArrival() > MAX_NO_DATA_MS) { @@ -130,7 +134,7 @@ private void calculatePosition() { } } - // zzzzzzzz + // Goodnight try { Thread.sleep(INTERVAL_CALCULATE_MS); } catch (InterruptedException e) { diff --git a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java index c3b3537..fbc9d8d 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/StationData.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; +// Record containing all data necessary for TeamData public record StationData( Station station, // The station Station nextStation, // The next station diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index f98dc9b..6fba92d 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -11,14 +11,14 @@ public class TeamData { private final DetectionList detections; // List with all relevant detections private final Map stations; // Station list - @Getter - private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private StationData currentStation; // Current station location private StationData previousStation; // Previous station location + @Getter + private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private final int totalDistance; // Total distance of the track + private final float maxDeviance; // Maximum deviance the animation can have from the reality @Getter private final Position position; // Data to send to the websocket - private final float maxDeviance; // Maximum deviance the animation can have from the reality public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { @@ -33,7 +33,7 @@ public TeamData(int teamId, int interval, List stations, int averageAmo totalDistance ) )); - // Pre-populate with some data + // Pre-populate with some default values this.stations.forEach((stationId, stationData) -> stationData.times().add( (long) (((stationData.nextStation().getDistanceFromStart() - stationData.station().getDistanceFromStart() + totalDistance) % totalDistance) / sprintingSpeed) )); @@ -88,7 +88,7 @@ public void updatePosition() { double theoreticalProgress = normalize(position.getProgress() + (position.getSpeed() * milliSecondsSince)); // Arrive at next station at timestamp y and progress z - double median = getMedian(currentStation.times()); + double median = getMedian(); double nextStationArrival = currentTime + median; double goalProgress = currentStation.nextProgress(); @@ -109,8 +109,8 @@ public void updatePosition() { } // Get the medium of the average times - private long getMedian(List times) { - List sortedList = new ArrayList<>(times); + private long getMedian() { + List sortedList = new ArrayList<>(currentStation.times()); Collections.sort(sortedList); int size = sortedList.size(); From f23c84cfab24b1f17cf7760839ff94fc785399ef Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 23 Apr 2024 15:08:39 +0200 Subject: [PATCH 72/90] deleted simplepositioner --- .../positioner/simple/CircularQueue.java | 21 ---- .../positioner/simple/SimplePositioner.java | 102 ------------------ 2 files changed, 123 deletions(-) delete mode 100644 src/main/java/telraam/logic/positioner/simple/CircularQueue.java delete mode 100644 src/main/java/telraam/logic/positioner/simple/SimplePositioner.java diff --git a/src/main/java/telraam/logic/positioner/simple/CircularQueue.java b/src/main/java/telraam/logic/positioner/simple/CircularQueue.java deleted file mode 100644 index ae101ed..0000000 --- a/src/main/java/telraam/logic/positioner/simple/CircularQueue.java +++ /dev/null @@ -1,21 +0,0 @@ -package telraam.logic.positioner.simple; - -import java.util.LinkedList; - -public class CircularQueue extends LinkedList { - - private final int maxSize; - public CircularQueue(int maxSize) { - this.maxSize = maxSize; - } - - @Override - public boolean add(T e) { - if (size() >= this.maxSize) { - removeFirst(); - } - - return super.add(e); - } - -} diff --git a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java b/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java deleted file mode 100644 index fa6a395..0000000 --- a/src/main/java/telraam/logic/positioner/simple/SimplePositioner.java +++ /dev/null @@ -1,102 +0,0 @@ -package telraam.logic.positioner.simple; - -import org.jdbi.v3.core.Jdbi; -import telraam.database.daos.BatonSwitchoverDAO; -import telraam.database.daos.StationDAO; -import telraam.database.daos.TeamDAO; -import telraam.database.models.BatonSwitchover; -import telraam.database.models.Detection; -import telraam.database.models.Station; -import telraam.database.models.Team; -import telraam.logic.positioner.Position; -import telraam.logic.positioner.PositionSender; -import telraam.logic.positioner.Positioner; - -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class SimplePositioner implements Positioner { - private static final Logger logger = Logger.getLogger(SimplePositioner.class.getName()); - private final int QUEUE_SIZE = 50; - private final int MIN_RSSI = -85; - private final int DEBOUNCE_TIMEOUT = 1; - private boolean debounceScheduled; - private final ScheduledExecutorService scheduler; - private final PositionSender positionSender; - private final Map batonIdToTeam; - private final Map> teamDetections; - private final List stations; - private final Map teamPositions; - - public SimplePositioner(Jdbi jdbi) { - this.debounceScheduled = false; - this.scheduler = Executors.newScheduledThreadPool(1); - this.positionSender = new PositionSender(); - this.batonIdToTeam = new HashMap<>(); - this.teamDetections = new HashMap<>(); - this.teamPositions = new HashMap<>(); - - TeamDAO teamDAO = jdbi.onDemand(TeamDAO.class); - List teams = teamDAO.getAll(); - for (Team team : teams) { - teamDetections.put(team.getId(), new CircularQueue<>(QUEUE_SIZE)); - teamPositions.put(team.getId(), new Position(team.getId())); - } - List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); - switchovers.sort(Comparator.comparing(BatonSwitchover::getTimestamp)); - - for (BatonSwitchover switchover : switchovers) { - batonIdToTeam.put(switchover.getNewBatonId(), teamDAO.getById(switchover.getTeamId()).get()); - } - - List stationList = jdbi.onDemand(StationDAO.class).getAll(); - stationList.sort(Comparator.comparing(Station::getDistanceFromStart)); - stations = stationList.stream().map(Station::getId).toList(); - } - - private void calculatePositions() { - logger.info("SimplePositioner: Calculating positions..."); - for (Map.Entry> entry : teamDetections.entrySet()) { - List detections = teamDetections.get(entry.getKey()); - detections.sort(Comparator.comparing(Detection::getTimestamp)); - - int currentStationRssi = MIN_RSSI; - int currentStationPosition = 0; - for (Detection detection : detections) { - if (detection.getRssi() > currentStationRssi) { - currentStationRssi = detection.getRssi(); - currentStationPosition = detection.getStationId(); - } - } - - float progress = ((float) 100 / stations.size()) * currentStationPosition; - teamPositions.get(entry.getKey()).setProgress(progress); - } - - positionSender.send(teamPositions.values().stream().toList()); - logger.info("SimplePositioner: Done calculating positions"); - } - - public synchronized void handle(Detection detection) { - Team team = batonIdToTeam.get(detection.getBatonId()); - teamDetections.get(team.getId()).add(detection); - - if (!debounceScheduled) { - debounceScheduled = true; - scheduler.schedule(() -> { - try { - calculatePositions(); - } catch (Exception e) { - logger.log(Level.SEVERE, e.getMessage(), e); - } - debounceScheduled = false; - }, DEBOUNCE_TIMEOUT, TimeUnit.SECONDS); - } - } -} From 74adeb20f70845c3dbacd4a0a4d3f19bee0f172a Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 23 Apr 2024 15:09:45 +0200 Subject: [PATCH 73/90] renamed the only reference left to average as it somehow still causes confusion --- .../telraam/logic/positioner/nostradamus/Nostradamus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 4b503b3..7cbab86 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -24,7 +24,7 @@ public class Nostradamus implements Positioner { private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching baton switchovers (in milliseconds) private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by private final int MAX_NO_DATA_MS = 30000; // Send a stationary position after receiving no station update for x amount of milliseconds - private final int AVERAGE_AMOUNT = 10; // Calculate the median running speed of the last x intervals + private final int MEDIAN_AMOUNT = 10; // Calculate the median running speed of the last x intervals private final double AVERAGE_SPRINTING_SPEED_M_MS = 0.00684; // Average sprinting speed meters / milliseconds private final int MIN_RSSI = -84; // Minimum rssi strength for a detection private final int FINISH_OFFSET_M = 0; // Distance between the last station and the finish in meters @@ -60,7 +60,7 @@ private Map getTeamData() { return teams.stream().collect(Collectors.toMap( Team::getId, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, AVERAGE_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET_M) + team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, MEDIAN_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET_M) )); } From 44ea73fa262c0f4069a32b5597fdf8ce7666d69d Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 23 Apr 2024 15:11:05 +0200 Subject: [PATCH 74/90] shorten fetch interval --- .../java/telraam/logic/positioner/nostradamus/Nostradamus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 7cbab86..558ac38 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -21,7 +21,7 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections (in milliseconds) - private final int INTERVAL_FETCH_MS = 60000; // Interval between fetching baton switchovers (in milliseconds) + private final int INTERVAL_FETCH_MS = 10000; // Interval between fetching baton switchovers (in milliseconds) private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by private final int MAX_NO_DATA_MS = 30000; // Send a stationary position after receiving no station update for x amount of milliseconds private final int MEDIAN_AMOUNT = 10; // Calculate the median running speed of the last x intervals From bdaa067d4c710c1d1e77207a2d7b760c607961fd Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 23 Apr 2024 15:29:36 +0200 Subject: [PATCH 75/90] removed simplepositioner --- src/main/java/telraam/App.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 0d79b23..4f4348c 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -1,11 +1,11 @@ package telraam; import io.dropwizard.core.Application; +import io.dropwizard.core.setup.Bootstrap; +import io.dropwizard.core.setup.Environment; import io.dropwizard.jdbi3.JdbiFactory; import io.dropwizard.jdbi3.bundles.JdbiExceptionsBundle; import io.dropwizard.jersey.setup.JerseyEnvironment; -import io.dropwizard.core.setup.Bootstrap; -import io.dropwizard.core.setup.Environment; import io.federecio.dropwizard.swagger.SwaggerBundle; import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration; import jakarta.servlet.DispatcherType; @@ -25,13 +25,10 @@ import telraam.logic.lapper.slapper.Slapper; import telraam.logic.positioner.Positioner; import telraam.logic.positioner.nostradamus.Nostradamus; -import telraam.logic.positioner.simple.SimplePositioner; import telraam.station.FetcherFactory; -import telraam.station.websocket.WebsocketFetcher; import telraam.util.AcceptedLapsUtil; import telraam.websocket.WebSocketConnection; -import java.io.IOException; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; @@ -93,11 +90,11 @@ public void run(AppConfiguration configuration, Environment environment) { // Register websocket endpoint JettyWebSocketServletContainerInitializer.configure( - environment.getApplicationContext(), - (servletContext, wsContainer) -> { - wsContainer.setMaxTextMessageSize(65535); - wsContainer.addMapping("/ws", (req, res) -> new WebSocketConnection()); - } + environment.getApplicationContext(), + (servletContext, wsContainer) -> { + wsContainer.setMaxTextMessageSize(65535); + wsContainer.addMapping("/ws", (req, res) -> new WebSocketConnection()); + } ); // Add api resources @@ -143,7 +140,6 @@ public void run(AppConfiguration configuration, Environment environment) { // Set up positioners Set positioners = new HashSet<>(); -// positioners.add(new SimplePositioner(this.database)); positioners.add(new Nostradamus(this.database)); // Start fetch thread for each station From b5cb3d5b2dcdfce9450eebb3746c9798f9c35a8c Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 23 Apr 2024 16:33:55 +0200 Subject: [PATCH 76/90] only send the standing still position once every interval --- .../java/telraam/logic/positioner/nostradamus/Nostradamus.java | 1 + .../java/telraam/logic/positioner/nostradamus/TeamData.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 558ac38..825d250 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -131,6 +131,7 @@ private void calculatePosition() { entry.getValue().getPosition().getProgress() )) ); + entry.getValue().setPreviousStationArrival(entry.getValue().getPreviousStationArrival() + MAX_NO_DATA_MS); } } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java index 6fba92d..c34a016 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java @@ -1,6 +1,7 @@ package telraam.logic.positioner.nostradamus; import lombok.Getter; +import lombok.Setter; import telraam.database.models.Detection; import telraam.database.models.Station; import telraam.logic.positioner.Position; @@ -13,7 +14,7 @@ public class TeamData { private final Map stations; // Station list private StationData currentStation; // Current station location private StationData previousStation; // Previous station location - @Getter + @Getter @Setter private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private final int totalDistance; // Total distance of the track private final float maxDeviance; // Maximum deviance the animation can have from the reality From 9b0c73327063b2b442057a48c3a1677e3d2a9faf Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 23 Apr 2024 16:34:32 +0200 Subject: [PATCH 77/90] fix(ws-fetcher): remove duplicate close handler --- .../java/telraam/station/websocket/WebsocketFetcher.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/main/java/telraam/station/websocket/WebsocketFetcher.java b/src/main/java/telraam/station/websocket/WebsocketFetcher.java index 62e9996..3d49016 100644 --- a/src/main/java/telraam/station/websocket/WebsocketFetcher.java +++ b/src/main/java/telraam/station/websocket/WebsocketFetcher.java @@ -103,15 +103,6 @@ public void fetch() { } this.fetch(); }); - websocketClient.addOnCloseHandler(() -> { - this.logger.severe(String.format("Websocket for station %s got closed", station.getName())); - try { - Thread.sleep(Fetcher.ERROR_TIMEOUT_MS); - } catch (InterruptedException e) { - logger.severe(e.getMessage()); - } - this.fetch(); - }); websocketClient.addMessageHandler((String msg) -> { //Insert detections List new_detections = new ArrayList<>(); From 413e8556492f38e276f74aeb64e381cb8067c368 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 23 Apr 2024 16:39:00 +0200 Subject: [PATCH 78/90] fix(ws-fetcher): infinite timeout --- src/main/java/telraam/station/websocket/WebsocketClient.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java index 25b7bb4..260baee 100644 --- a/src/main/java/telraam/station/websocket/WebsocketClient.java +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -27,6 +27,8 @@ public void listen() throws RuntimeException { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.setDefaultMaxTextMessageBufferSize(100 * 1048576); // 100Mb + container.setDefaultMaxSessionIdleTimeout(0); + container.setAsyncSendTimeout(0); container.connectToServer(this, endpoint); } catch (Exception e) { throw new RuntimeException(e); From d3424143ee459d0867631aa50e45dd3392f0e1a0 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 23 Apr 2024 21:46:59 +0200 Subject: [PATCH 79/90] fix(ws-fetcher): let websocket timeout fail silently --- .../telraam/station/websocket/WebsocketClient.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java index 260baee..dbab406 100644 --- a/src/main/java/telraam/station/websocket/WebsocketClient.java +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -1,6 +1,7 @@ package telraam.station.websocket; import jakarta.websocket.*; +import org.eclipse.jetty.websocket.core.exception.WebSocketTimeoutException; import java.net.URI; @@ -27,14 +28,21 @@ public void listen() throws RuntimeException { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.setDefaultMaxTextMessageBufferSize(100 * 1048576); // 100Mb - container.setDefaultMaxSessionIdleTimeout(0); - container.setAsyncSendTimeout(0); + container.setDefaultMaxSessionIdleTimeout(60); container.connectToServer(this, endpoint); } catch (Exception e) { throw new RuntimeException(e); } } + @OnError + public void onError(Session session, Throwable error) throws Throwable { + if (error instanceof WebSocketTimeoutException) { + return; + } + throw error; + } + @OnOpen public void onOpen(Session session) { this.session = session; From 7e06cb1539cefbf90089611cde79160afc68c2df Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Wed, 24 Apr 2024 09:20:01 +0200 Subject: [PATCH 80/90] fix(websocket): it uses MS -_- --- src/main/java/telraam/station/websocket/WebsocketClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/telraam/station/websocket/WebsocketClient.java b/src/main/java/telraam/station/websocket/WebsocketClient.java index dbab406..7767258 100644 --- a/src/main/java/telraam/station/websocket/WebsocketClient.java +++ b/src/main/java/telraam/station/websocket/WebsocketClient.java @@ -28,7 +28,7 @@ public void listen() throws RuntimeException { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.setDefaultMaxTextMessageBufferSize(100 * 1048576); // 100Mb - container.setDefaultMaxSessionIdleTimeout(60); + container.setDefaultMaxSessionIdleTimeout(60000); container.connectToServer(this, endpoint); } catch (Exception e) { throw new RuntimeException(e); From 8ecc20801ac5a909c011f7d24757fcdc83f05ce4 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 1 Apr 2025 22:23:54 +0200 Subject: [PATCH 81/90] support multiple positioners --- src/main/java/telraam/App.java | 1 + .../telraam/api/PositionSourceResource.java | 20 ++++++++++++++ .../database/daos/PositionSourceDAO.java | 27 +++++++++++++++++++ .../database/models/PositionSource.java | 17 ++++++++++++ .../logic/positioner/PositionSender.java | 4 +-- .../positioner/nostradamus/Nostradamus.java | 15 +++++++---- .../db/migration/V17__Add_position_source.sql | 6 +++++ 7 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 src/main/java/telraam/api/PositionSourceResource.java create mode 100644 src/main/java/telraam/database/daos/PositionSourceDAO.java create mode 100644 src/main/java/telraam/database/models/PositionSource.java create mode 100644 src/main/resources/db/migration/V17__Add_position_source.sql diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 4f4348c..859270c 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -105,6 +105,7 @@ public void run(AppConfiguration configuration, Environment environment) { jersey.register(new LapResource(database.onDemand(LapDAO.class))); jersey.register(new TeamResource(database.onDemand(TeamDAO.class), database.onDemand(BatonSwitchoverDAO.class))); jersey.register(new LapSourceResource(database.onDemand(LapSourceDAO.class))); + jersey.register(new PositionSourceResource(database.onDemand(PositionSourceDAO.class))); jersey.register(new BatonSwitchoverResource(database.onDemand(BatonSwitchoverDAO.class))); jersey.register(new LapSourceSwitchoverResource(database.onDemand(LapSourceSwitchoverDAO.class))); jersey.register(new AcceptedLapsResource()); diff --git a/src/main/java/telraam/api/PositionSourceResource.java b/src/main/java/telraam/api/PositionSourceResource.java new file mode 100644 index 0000000..f59c7bb --- /dev/null +++ b/src/main/java/telraam/api/PositionSourceResource.java @@ -0,0 +1,20 @@ +package telraam.api; + +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import telraam.database.daos.DAO; +import telraam.database.models.PositionSource; + + +import java.awt.*; + +@Path("/position-source") +@Tag(name = "Position Source") +@Produces(MediaType.APPLICATION_JSON) +public class PositionSourceResource extends AbstractListableResource { + public PositionSourceResource(DAO dao) { + super(dao); + } +} diff --git a/src/main/java/telraam/database/daos/PositionSourceDAO.java b/src/main/java/telraam/database/daos/PositionSourceDAO.java new file mode 100644 index 0000000..36f172f --- /dev/null +++ b/src/main/java/telraam/database/daos/PositionSourceDAO.java @@ -0,0 +1,27 @@ +package telraam.database.daos; + +import org.jdbi.v3.sqlobject.config.RegisterBeanMapper; +import org.jdbi.v3.sqlobject.customizer.Bind; +import org.jdbi.v3.sqlobject.customizer.BindBean; +import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; +import org.jdbi.v3.sqlobject.statement.SqlQuery; +import org.jdbi.v3.sqlobject.statement.SqlUpdate; +import telraam.database.models.PositionSource; + +import java.util.List; +import java.util.Optional; + +public interface PositionSourceDAO extends DAO { + @Override + @SqlQuery("SELECT * FROM position_source") + @RegisterBeanMapper(PositionSource.class) + List getAll(); + + @SqlUpdate("INSERT INTO position_source (name) VALUES (:name)") + @GetGeneratedKeys({"id"}) + int insert(@BindBean PositionSource positionSource); + + @SqlQuery("SELECT * FROM position_source WHERE name = :name") + @RegisterBeanMapper(PositionSource.class) + Optional getByName(@Bind("name") String name); +} diff --git a/src/main/java/telraam/database/models/PositionSource.java b/src/main/java/telraam/database/models/PositionSource.java new file mode 100644 index 0000000..19d2fd1 --- /dev/null +++ b/src/main/java/telraam/database/models/PositionSource.java @@ -0,0 +1,17 @@ +package telraam.database.models; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class PositionSource { + private Integer id; + private String name; + + public PositionSource(String name) { + this.name = name; + } +} diff --git a/src/main/java/telraam/logic/positioner/PositionSender.java b/src/main/java/telraam/logic/positioner/PositionSender.java index 5e779dc..e909d5e 100644 --- a/src/main/java/telraam/logic/positioner/PositionSender.java +++ b/src/main/java/telraam/logic/positioner/PositionSender.java @@ -8,8 +8,8 @@ public class PositionSender { private final WebSocketMessage> message = new WebSocketMessage<>(); - public PositionSender() { - this.message.setTopic("position"); + public PositionSender(String name) { + this.message.setTopic("position_" + name); } public void send(List positions) { diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java index 825d250..2fa7a85 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java @@ -2,12 +2,10 @@ import org.jdbi.v3.core.Jdbi; import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.PositionSourceDAO; import telraam.database.daos.StationDAO; import telraam.database.daos.TeamDAO; -import telraam.database.models.BatonSwitchover; -import telraam.database.models.Detection; -import telraam.database.models.Station; -import telraam.database.models.Team; +import telraam.database.models.*; import telraam.logic.positioner.Position; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; @@ -20,6 +18,7 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); + private final String SOURCE_NAME = "nostradamus"; private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections (in milliseconds) private final int INTERVAL_FETCH_MS = 10000; // Interval between fetching baton switchovers (in milliseconds) private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by @@ -38,6 +37,12 @@ public class Nostradamus implements Positioner { public Nostradamus(Jdbi jdbi) { this.jdbi = jdbi; + + PositionSourceDAO positionSourceDAO = jdbi.onDemand(PositionSourceDAO.class); + if (positionSourceDAO.getByName(SOURCE_NAME).isEmpty()) { + positionSourceDAO.insert(new PositionSource(SOURCE_NAME)); + } + this.newDetections = new ArrayList<>(); this.detectionLock = new ReentrantLock(); this.dataLock = new ReentrantLock(); @@ -46,7 +51,7 @@ public Nostradamus(Jdbi jdbi) { this.batonToTeam = new HashMap<>(); this.teamData = getTeamData(); - this.positionSender = new PositionSender(); + this.positionSender = new PositionSender(SOURCE_NAME); new Thread(this::fetch).start(); new Thread(this::calculatePosition).start(); diff --git a/src/main/resources/db/migration/V17__Add_position_source.sql b/src/main/resources/db/migration/V17__Add_position_source.sql new file mode 100644 index 0000000..fa8c759 --- /dev/null +++ b/src/main/resources/db/migration/V17__Add_position_source.sql @@ -0,0 +1,6 @@ +create table position_source +( + id serial not null + constraint position_source_pk primary key, + name varchar(255) not null unique +); \ No newline at end of file From f22a61fe320077aeb342b852222baf4b92e7ab4d Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 1 Apr 2025 22:31:47 +0200 Subject: [PATCH 82/90] adjust position message --- .../java/telraam/logic/positioner/PositionSender.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/PositionSender.java b/src/main/java/telraam/logic/positioner/PositionSender.java index e909d5e..54166d0 100644 --- a/src/main/java/telraam/logic/positioner/PositionSender.java +++ b/src/main/java/telraam/logic/positioner/PositionSender.java @@ -4,16 +4,22 @@ import telraam.websocket.WebSocketMessageSingleton; import java.util.List; +import java.util.Map; public class PositionSender { private final WebSocketMessage> message = new WebSocketMessage<>(); + private final String name; public PositionSender(String name) { - this.message.setTopic("position_" + name); + this.message.setTopic("position"); + this.name = name; } public void send(List positions) { - this.message.setData(positions); + Map data = Map.of( + "positioner", this.name, + "positions", positions + ); WebSocketMessageSingleton.getInstance().sendToAll(this.message); } From c165adcfe4e49ea96ccf80d1d639ff146c3619aa Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Mon, 7 Apr 2025 21:47:09 +0200 Subject: [PATCH 83/90] chore(ci): bump version number of ci actions --- .github/workflows/gradle.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index f45a655..b761045 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -15,15 +15,16 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up JDK 17 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: + distribution: "oracle" java-version: 17 - name: Cache Gradle packages - uses: actions/cache@v1 + uses: actions/cache@v4 with: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} From 2f0a471aa6201e2a0d664a04a6d174b81364049f Mon Sep 17 00:00:00 2001 From: Topvennie Date: Mon, 7 Apr 2025 21:57:33 +0200 Subject: [PATCH 84/90] fix: send position data to ws --- .../java/telraam/logic/positioner/PositionSender.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/telraam/logic/positioner/PositionSender.java b/src/main/java/telraam/logic/positioner/PositionSender.java index 54166d0..a111746 100644 --- a/src/main/java/telraam/logic/positioner/PositionSender.java +++ b/src/main/java/telraam/logic/positioner/PositionSender.java @@ -7,7 +7,7 @@ import java.util.Map; public class PositionSender { - private final WebSocketMessage> message = new WebSocketMessage<>(); + private final WebSocketMessage> message = new WebSocketMessage<>(); private final String name; public PositionSender(String name) { @@ -16,11 +16,13 @@ public PositionSender(String name) { } public void send(List positions) { - Map data = Map.of( + Map payload = Map.of( "positioner", this.name, "positions", positions ); - WebSocketMessageSingleton.getInstance().sendToAll(this.message); + + message.setData(payload); + WebSocketMessageSingleton.getInstance().sendToAll(message); } } From e4c139011897a3a4a0f84531d24704e2f2459358 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Thu, 10 Apr 2025 15:53:29 +0200 Subject: [PATCH 85/90] add stationary positioner --- .../positioner/Stationary/Stationary.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/telraam/logic/positioner/Stationary/Stationary.java diff --git a/src/main/java/telraam/logic/positioner/Stationary/Stationary.java b/src/main/java/telraam/logic/positioner/Stationary/Stationary.java new file mode 100644 index 0000000..b870802 --- /dev/null +++ b/src/main/java/telraam/logic/positioner/Stationary/Stationary.java @@ -0,0 +1,56 @@ +package telraam.logic.positioner.Stationary; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.PositionSourceDAO; +import telraam.database.daos.TeamDAO; +import telraam.database.models.Detection; +import telraam.database.models.PositionSource; +import telraam.database.models.Team; +import telraam.logic.positioner.Position; +import telraam.logic.positioner.PositionSender; +import telraam.logic.positioner.Positioner; +import telraam.logic.positioner.nostradamus.Nostradamus; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +public class Stationary implements Positioner { + private static final Logger logger = Logger.getLogger(Stationary.class.getName()); + private final String SOURCE_NAME = "stationary"; + private final int INTERVAL_UPDATE_MS = 60000; + private final Jdbi jdbi; + private final PositionSender positionSender; + public Stationary(Jdbi jdbi) { + this.jdbi = jdbi; + this.positionSender = new PositionSender(SOURCE_NAME); + + // Add as source + PositionSourceDAO positionSourceDAO = jdbi.onDemand(PositionSourceDAO.class); + if (positionSourceDAO.getByName(SOURCE_NAME).isEmpty()) { + positionSourceDAO.insert(new PositionSource(SOURCE_NAME)); + } + + new Thread(this::update).start(); + } + + private void update() { + // Keep sending updates in case Loxsi ever restarts + while (true) { + long timestamp = System.currentTimeMillis(); + List teams = jdbi.onDemand(TeamDAO.class).getAll(); + + List positions = teams.stream().map(t -> new Position(t.getId(), 0, 0, timestamp)).toList(); + positionSender.send(positions); + + try { + Thread.sleep(INTERVAL_UPDATE_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + } + + @Override + public void handle(Detection detection) {} +} From 5925b8618ea2a20eabddeb467d9b97e837e08902 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Thu, 10 Apr 2025 16:09:24 +0200 Subject: [PATCH 86/90] rework nostradamus logic --- src/main/java/telraam/App.java | 6 +- .../telraam/database/models/Detection.java | 7 + .../telraam/logic/positioner/Position.java | 60 ++++--- .../positioner/Stationary/Stationary.java | 2 - .../CircularQueueV1.java} | 6 +- .../DetectionListV1.java} | 6 +- .../NostradamusV1.java} | 22 +-- .../StationDataV1.java} | 10 +- .../{TeamData.java => v1/TeamDataV1.java} | 34 ++-- .../nostradamus/v2/Nostradamus.java | 143 ++++++++++++++++ .../nostradamus/v2/StationData.java | 10 ++ .../nostradamus/v2/TeamHandler.java | 162 ++++++++++++++++++ 12 files changed, 402 insertions(+), 66 deletions(-) rename src/main/java/telraam/logic/positioner/nostradamus/{CircularQueue.java => v1/CircularQueueV1.java} (66%) rename src/main/java/telraam/logic/positioner/nostradamus/{DetectionList.java => v1/DetectionListV1.java} (92%) rename src/main/java/telraam/logic/positioner/nostradamus/{Nostradamus.java => v1/NostradamusV1.java} (89%) rename src/main/java/telraam/logic/positioner/nostradamus/{StationData.java => v1/StationDataV1.java} (81%) rename src/main/java/telraam/logic/positioner/nostradamus/{TeamData.java => v1/TeamDataV1.java} (76%) create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java create mode 100644 src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 859270c..92591df 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -24,7 +24,9 @@ import telraam.logic.lapper.robust.RobustLapper; import telraam.logic.lapper.slapper.Slapper; import telraam.logic.positioner.Positioner; -import telraam.logic.positioner.nostradamus.Nostradamus; +import telraam.logic.positioner.Stationary.Stationary; +import telraam.logic.positioner.nostradamus.v2.Nostradamus; +import telraam.logic.positioner.nostradamus.v1.NostradamusV1; import telraam.station.FetcherFactory; import telraam.util.AcceptedLapsUtil; import telraam.websocket.WebSocketConnection; @@ -141,7 +143,9 @@ public void run(AppConfiguration configuration, Environment environment) { // Set up positioners Set positioners = new HashSet<>(); + positioners.add(new Stationary(this.database)); positioners.add(new Nostradamus(this.database)); + positioners.add(new NostradamusV1(this.database)); // Start fetch thread for each station FetcherFactory fetcherFactory = new FetcherFactory(this.database, lappers, positioners); diff --git a/src/main/java/telraam/database/models/Detection.java b/src/main/java/telraam/database/models/Detection.java index 4950feb..c00264b 100644 --- a/src/main/java/telraam/database/models/Detection.java +++ b/src/main/java/telraam/database/models/Detection.java @@ -37,4 +37,11 @@ public Detection(Integer id, Integer stationId, Integer rssi) { this.stationId = stationId; this.rssi = rssi; } + + public Detection(Integer id, Integer stationId, Integer rssi, Timestamp timestamp) { + this.id = id; + this.stationId = stationId; + this.rssi = rssi; + this.timestamp = timestamp; + } } diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 43f8e26..8d0d524 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -5,30 +5,36 @@ import lombok.Getter; import lombok.Setter; -@Getter @Setter @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) -public class Position { - private final int teamId; - private double progress; // Progress of the lap. Between 0-1 - private double speed; // Current speed. progress / millisecond - private long timestamp; // Timestamp in milliseconds - - public Position(int teamId) { - this.teamId = teamId; - this.progress = 0; - this.speed = 0; - this.timestamp = System.currentTimeMillis(); - } - - public Position(int teamId, double progress) { - this.teamId = teamId; - this.progress = progress; - this.speed = 0; - this.timestamp = System.currentTimeMillis(); - } - - public void update(double progress, double speed, long timestamp) { - this.progress = progress; - this.speed = speed; - this.timestamp = timestamp; - } -} +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record Position ( + int teamId, + double progress, + double speed, + long timestamp +) {} +//public class Position { +// private final int teamId; +// private double progress; // Progress of the lap. Between 0-1 +// private double speed; // Current speed. progress / millisecond +// private long timestamp; // Timestamp in milliseconds +// +// public Position(int teamId) { +// this.teamId = teamId; +// this.progress = 0; +// this.speed = 0; +// this.timestamp = System.currentTimeMillis(); +// } +// +// public Position(int teamId, double progress) { +// this.teamId = teamId; +// this.progress = progress; +// this.speed = 0; +// this.timestamp = System.currentTimeMillis(); +// } +// +// public void update(double progress, double speed, long timestamp) { +// this.progress = progress; +// this.speed = speed; +// this.timestamp = timestamp; +// } +//} diff --git a/src/main/java/telraam/logic/positioner/Stationary/Stationary.java b/src/main/java/telraam/logic/positioner/Stationary/Stationary.java index b870802..e34c8ef 100644 --- a/src/main/java/telraam/logic/positioner/Stationary/Stationary.java +++ b/src/main/java/telraam/logic/positioner/Stationary/Stationary.java @@ -9,9 +9,7 @@ import telraam.logic.positioner.Position; import telraam.logic.positioner.PositionSender; import telraam.logic.positioner.Positioner; -import telraam.logic.positioner.nostradamus.Nostradamus; -import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; diff --git a/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java b/src/main/java/telraam/logic/positioner/nostradamus/v1/CircularQueueV1.java similarity index 66% rename from src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java rename to src/main/java/telraam/logic/positioner/nostradamus/v1/CircularQueueV1.java index 1b2faae..95889cc 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/CircularQueue.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v1/CircularQueueV1.java @@ -1,12 +1,12 @@ -package telraam.logic.positioner.nostradamus; +package telraam.logic.positioner.nostradamus.v1; import java.util.LinkedList; // LinkedList with a maximum length -public class CircularQueue extends LinkedList { +public class CircularQueueV1 extends LinkedList { private final int maxSize; - public CircularQueue(int maxSize) { + public CircularQueueV1(int maxSize) { this.maxSize = maxSize; } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java b/src/main/java/telraam/logic/positioner/nostradamus/v1/DetectionListV1.java similarity index 92% rename from src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java rename to src/main/java/telraam/logic/positioner/nostradamus/v1/DetectionListV1.java index 30d5848..db7e0f6 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/DetectionList.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v1/DetectionListV1.java @@ -1,4 +1,4 @@ -package telraam.logic.positioner.nostradamus; +package telraam.logic.positioner.nostradamus.v1; import lombok.Getter; import telraam.database.models.Detection; @@ -9,7 +9,7 @@ import java.util.Comparator; import java.util.List; -public class DetectionList extends ArrayList { +public class DetectionListV1 extends ArrayList { private final int interval; private final List stations; @@ -17,7 +17,7 @@ public class DetectionList extends ArrayList { private Detection currentPosition; private Timestamp newestDetection; - public DetectionList(int interval, List stations) { + public DetectionListV1(int interval, List stations) { this.interval = interval; this.stations = stations.stream().sorted(Comparator.comparing(Station::getDistanceFromStart)).map(Station::getId).toList(); this.currentPosition = new Detection(-1, 0, -100); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/v1/NostradamusV1.java similarity index 89% rename from src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java rename to src/main/java/telraam/logic/positioner/nostradamus/v1/NostradamusV1.java index 2fa7a85..d8b875c 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v1/NostradamusV1.java @@ -1,4 +1,4 @@ -package telraam.logic.positioner.nostradamus; +package telraam.logic.positioner.nostradamus.v1; import org.jdbi.v3.core.Jdbi; import telraam.database.daos.BatonSwitchoverDAO; @@ -16,9 +16,9 @@ import java.util.logging.Logger; import java.util.stream.Collectors; -public class Nostradamus implements Positioner { - private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); - private final String SOURCE_NAME = "nostradamus"; +public class NostradamusV1 implements Positioner { + private static final Logger logger = Logger.getLogger(NostradamusV1.class.getName()); + private final String SOURCE_NAME = "nostradamus_v1"; private final int INTERVAL_CALCULATE_MS = 500; // How often to handle new detections (in milliseconds) private final int INTERVAL_FETCH_MS = 10000; // Interval between fetching baton switchovers (in milliseconds) private final int INTERVAL_DETECTIONS_MS = 3000; // Amount of milliseconds to group detections by @@ -30,12 +30,12 @@ public class Nostradamus implements Positioner { private final Jdbi jdbi; private final List newDetections; // Contains not yet handled detections private Map batonToTeam; // Baton ID to Team ID - private final Map teamData; // All team data + private final Map teamData; // All team data private final PositionSender positionSender; private final Lock detectionLock; private final Lock dataLock; - public Nostradamus(Jdbi jdbi) { + public NostradamusV1(Jdbi jdbi) { this.jdbi = jdbi; PositionSourceDAO positionSourceDAO = jdbi.onDemand(PositionSourceDAO.class); @@ -58,14 +58,14 @@ public Nostradamus(Jdbi jdbi) { } // Initiate the team data map - private Map getTeamData() { + private Map getTeamData() { List stations = jdbi.onDemand(StationDAO.class).getAll(); stations.sort(Comparator.comparing(Station::getDistanceFromStart)); List teams = jdbi.onDemand(TeamDAO.class).getAll(); return teams.stream().collect(Collectors.toMap( Team::getId, - team -> new TeamData(team.getId(), INTERVAL_DETECTIONS_MS, stations, MEDIAN_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET_M) + team -> new TeamDataV1(team.getId(), INTERVAL_DETECTIONS_MS, stations, MEDIAN_AMOUNT, AVERAGE_SPRINTING_SPEED_M_MS, FINISH_OFFSET_M) )); } @@ -128,12 +128,14 @@ private void calculatePosition() { // Send a stationary position if no new station data was received recently long now = System.currentTimeMillis(); - for (Map.Entry entry: teamData.entrySet()) { + for (Map.Entry entry: teamData.entrySet()) { if (now - entry.getValue().getPreviousStationArrival() > MAX_NO_DATA_MS) { positionSender.send( Collections.singletonList(new Position( entry.getKey(), - entry.getValue().getPosition().getProgress() + entry.getValue().getPosition().progress(), + 0, + System.currentTimeMillis() )) ); entry.getValue().setPreviousStationArrival(entry.getValue().getPreviousStationArrival() + MAX_NO_DATA_MS); diff --git a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/v1/StationDataV1.java similarity index 81% rename from src/main/java/telraam/logic/positioner/nostradamus/StationData.java rename to src/main/java/telraam/logic/positioner/nostradamus/v1/StationDataV1.java index fbc9d8d..15c7277 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/StationData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v1/StationDataV1.java @@ -1,4 +1,4 @@ -package telraam.logic.positioner.nostradamus; +package telraam.logic.positioner.nostradamus.v1; import telraam.database.models.Station; @@ -6,7 +6,7 @@ import java.util.List; // Record containing all data necessary for TeamData -public record StationData( +public record StationDataV1( Station station, // The station Station nextStation, // The next station List times, // List containing the times (in ms) that was needed to run from this station to the next one. @@ -14,7 +14,7 @@ public record StationData( float currentProgress, // The progress value of this station float nextProgress // The progress value of the next station ) { - public StationData() { + public StationDataV1() { this( new Station(-10), new Station(-9), @@ -25,11 +25,11 @@ public StationData() { ); } - public StationData(List stations, int index, int averageAmount, int totalDistance) { + public StationDataV1(List stations, int index, int averageAmount, int totalDistance) { this( stations.get(index), stations.get((index + 1) % stations.size()), - new CircularQueue<>(averageAmount), + new CircularQueueV1<>(averageAmount), index, (float) (stations.get(index).getDistanceFromStart() / totalDistance), (float) (stations.get((index + 1) % stations.size()).getDistanceFromStart() / totalDistance) diff --git a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java b/src/main/java/telraam/logic/positioner/nostradamus/v1/TeamDataV1.java similarity index 76% rename from src/main/java/telraam/logic/positioner/nostradamus/TeamData.java rename to src/main/java/telraam/logic/positioner/nostradamus/v1/TeamDataV1.java index c34a016..82de61b 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/TeamData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v1/TeamDataV1.java @@ -1,4 +1,4 @@ -package telraam.logic.positioner.nostradamus; +package telraam.logic.positioner.nostradamus.v1; import lombok.Getter; import lombok.Setter; @@ -7,27 +7,30 @@ import telraam.logic.positioner.Position; import java.util.*; +import java.util.logging.Logger; import java.util.stream.Collectors; -public class TeamData { - private final DetectionList detections; // List with all relevant detections - private final Map stations; // Station list - private StationData currentStation; // Current station location - private StationData previousStation; // Previous station location +public class TeamDataV1 { + private static final Logger logger = Logger.getLogger(TeamDataV1.class.getName()); + private final DetectionListV1 detections; // List with all relevant detections + private final Map stations; // Station list + private StationDataV1 currentStation; // Current station location + private StationDataV1 previousStation; // Previous station location @Getter @Setter private long previousStationArrival; // Arrival time of previous station. Used to calculate the average times private final int totalDistance; // Total distance of the track private final float maxDeviance; // Maximum deviance the animation can have from the reality @Getter - private final Position position; // Data to send to the websocket + private Position position; // Data to send to the websocket + private final int teamId; - public TeamData(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { + public TeamDataV1(int teamId, int interval, List stations, int averageAmount, double sprintingSpeed, int finishOffset) { stations.sort(Comparator.comparing(Station::getDistanceFromStart)); this.totalDistance = (int) (stations.get(stations.size() - 1).getDistanceFromStart() + finishOffset); this.stations = stations.stream().collect(Collectors.toMap( Station::getId, - station -> new StationData( + station -> new StationDataV1( stations, stations.indexOf(station), averageAmount, @@ -38,11 +41,12 @@ public TeamData(int teamId, int interval, List stations, int averageAmo this.stations.forEach((stationId, stationData) -> stationData.times().add( (long) (((stationData.nextStation().getDistanceFromStart() - stationData.station().getDistanceFromStart() + totalDistance) % totalDistance) / sprintingSpeed) )); - this.detections = new DetectionList(interval, stations); + this.detections = new DetectionListV1(interval, stations); this.previousStationArrival = System.currentTimeMillis(); - this.currentStation = new StationData(); // Will never trigger `isNextStation` for the first station - this.position = new Position(teamId); + this.currentStation = new StationDataV1(); // Will never trigger `isNextStation` for the first station this.maxDeviance = (float) 1 / stations.size(); + this.teamId = teamId; + this.position = new Position(teamId, 0, 0, System.currentTimeMillis()); } // Add a new detection @@ -85,8 +89,8 @@ public void updatePosition() { long currentTime = System.currentTimeMillis(); // Animation is currently at progress x - long milliSecondsSince = currentTime - position.getTimestamp(); - double theoreticalProgress = normalize(position.getProgress() + (position.getSpeed() * milliSecondsSince)); + long milliSecondsSince = currentTime - position.timestamp(); + double theoreticalProgress = normalize(position.progress() + (position.speed() * milliSecondsSince)); // Arrive at next station at timestamp y and progress z double median = getMedian(); @@ -106,7 +110,7 @@ public void updatePosition() { speed = normalize(goalProgress - theoreticalProgress) / (nextStationArrival - currentTime); } - position.update(progress, speed, currentTime); + position = new Position(teamId, progress, speed, currentTime); } // Get the medium of the average times diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java new file mode 100644 index 0000000..129c137 --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java @@ -0,0 +1,143 @@ +package telraam.logic.positioner.nostradamus.v2; + +import org.jdbi.v3.core.Jdbi; +import telraam.database.daos.BatonSwitchoverDAO; +import telraam.database.daos.PositionSourceDAO; +import telraam.database.daos.StationDAO; +import telraam.database.models.*; +import telraam.logic.positioner.Position; +import telraam.logic.positioner.PositionSender; +import telraam.logic.positioner.Positioner; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class Nostradamus implements Positioner { + private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); + private final String SOURCE_NAME = "nostradamus_v2"; + private final int MIN_RSSI = -90; // Minimum rssi strength that a detections needs to have + private final int INTERVAL_FETCH_MS = 10000; + private final int INTERVAL_UPDATE_MS = 200; + private final int LENGTH_OFFSET = 10; // Distance from the last station to the finish in meter + private final Jdbi jdbi; + private final PositionSender positionSender; + ConcurrentHashMap> newDetections; + private final Map teamHandlers; + private final Map stationData; + + public Nostradamus(Jdbi jdbi) { + this.jdbi = jdbi; + + // Add as source + PositionSourceDAO positionSourceDAO = jdbi.onDemand(PositionSourceDAO.class); + if (positionSourceDAO.getByName(SOURCE_NAME).isEmpty()) { + positionSourceDAO.insert(new PositionSource(SOURCE_NAME)); + } + + this.positionSender = new PositionSender(SOURCE_NAME); + this.newDetections = new ConcurrentHashMap<>(); + this.teamHandlers = new ConcurrentHashMap<>(); + this.stationData = new HashMap<>(); + + // Initialize station data list + List stations = this.jdbi.onDemand(StationDAO.class).getAll(); + stations.sort(Comparator.comparing(Station::getDistanceFromStart)); + int length = (int) (stations.get(stations.size() - 1).getDistanceFromStart() + LENGTH_OFFSET); + for (int i = 0; i < stations.size(); i++) { + Station station = stations.get(i); + int nextIdx = (i + 1) % stations.size(); + int distanceToNext = (int) ((stations.get(nextIdx).getDistanceFromStart() - station.getDistanceFromStart() + length ) % length); + this.stationData.put(station.getId(), new StationData( + distanceToNext, + station.getDistanceFromStart() / length, + (double) distanceToNext / length, + stations.get(nextIdx).getId())); + } + + new Thread(this::fetch).start(); + new Thread(this::update).start(); + } + + // Fetch updates team handlers based on switchovers + private void fetch() { + while (true) { + List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); + + Map batonToTeam = switchovers.stream().sorted( + Comparator.comparing(BatonSwitchover::getTimestamp) + ).collect(Collectors.toMap( + BatonSwitchover::getNewBatonId, + BatonSwitchover::getTeamId, + (existing, replacement) -> replacement + )); + + for (Map.Entry entry: batonToTeam.entrySet()) { + teamHandlers.compute(entry.getValue(), (teamId, existingTeam) -> { + if (existingTeam == null) { + return new TeamHandler(teamId, new AtomicInteger(entry.getKey()), stationData); + } else { + existingTeam.batonId.set(entry.getKey()); + return existingTeam; + } + }); + } + + try { + Thread.sleep(INTERVAL_FETCH_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + } + + // Update handles all new detections and sends new positions + private void update() { + List positions = new ArrayList<>(); + + while (true) { + positions.clear(); + + for (TeamHandler team : teamHandlers.values()) { + ConcurrentLinkedQueue queue = newDetections.get(team.batonId.get()); + if (queue != null && !queue.isEmpty()) { + List copy = new ArrayList<>(); + Detection d; + while ((d = queue.poll()) != null) { + copy.add(d); + } + + team.update(copy); + } + + Position position = team.getPosition(); + if (position != null) { + positions.add(position); + } + } + + if (!positions.isEmpty()) { + positionSender.send(positions); + } + + try { + Thread.sleep(INTERVAL_UPDATE_MS); + } catch (InterruptedException e) { + logger.severe(e.getMessage()); + } + } + } + + @Override + public void handle(Detection detection) { + if (detection.getRssi() > MIN_RSSI) { + newDetections + .computeIfAbsent(detection.getBatonId(), k -> new ConcurrentLinkedQueue<>()) + .add(detection); + } + } + +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java new file mode 100644 index 0000000..442de6e --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java @@ -0,0 +1,10 @@ +package telraam.logic.positioner.nostradamus.v2; + +// Record containing all data regarding a station +public record StationData( + int distanceToNext, // Meters until the next station + double progress, // Location of station in progress + double progressToNext, // Progress until you arrive at the next station + int nextStationId // ID of the next station +) { +} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java new file mode 100644 index 0000000..347d26b --- /dev/null +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java @@ -0,0 +1,162 @@ +package telraam.logic.positioner.nostradamus.v2; + +import telraam.database.models.Detection; +import telraam.logic.positioner.Position; + +import java.sql.Timestamp; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Logger; + +public class TeamHandler { + private static final Logger logger = Logger.getLogger(TeamHandler.class.getName()); + // TODO: This won't be as effective for tracks with different lengths + private final double MAX_SPEED = 0.00003; // Max speed progress / ms + private final double AVG_SPEED = 0.006; // Average sprinting speed (m / ms), results in a lap of 55 seconds in the 12ul + private final int INTERVAL = 2000; // Only keep detections in a x ms interval + private final int MAX_TIMES = 20; // Amount of speeds to keep track of to determine the median + private final int teamId; + public AtomicInteger batonId; + + private final Map stationDataMap; // Map from station id to StationData + private final Map> stationSpeeds; // Avg speed (progress / ms) to go from a stationId to the next + private int currentStation; // Current station id + private Position lastPosition; + private final Queue positions; + + private final LinkedList detections; + private Detection currentStationDetection; + + public TeamHandler(int teamId, AtomicInteger batonId, Map stationDataMap) { + this.teamId = teamId; + this.batonId = batonId; + this.stationDataMap = stationDataMap; + + this.stationSpeeds = new HashMap<>(); + this.positions = new ArrayDeque<>(); + this.detections = new LinkedList<>(); + + this.currentStation = -1; + this.lastPosition = new Position(0, 0, 0, 0); + this.detections.add(new Detection(-1, -1, -1000, new Timestamp(0))); + + // Populate the stationSpeeds map with default values + for (Map.Entry entry: stationDataMap.entrySet()) { + this.stationSpeeds.put(entry.getKey(), new ArrayList<>()); + double progress = stationDataMap.get(entry.getKey()).progressToNext(); + double time = entry.getValue().distanceToNext() / AVG_SPEED; + this.stationSpeeds.get(entry.getKey()).add(progress / time); + } + } + + public void update(List detections) { + boolean newStation = handleDetection(detections); + if (!newStation) { + return; + } + + StationData station = stationDataMap.get(currentStation); + long timestamp = System.currentTimeMillis(); + + double currentProgress = normalize(lastPosition.progress() + lastPosition.speed() * (timestamp - lastPosition.timestamp())); // Where is the animation now + + double maxDeviation = station.progressToNext(); + if (circularDistance(currentProgress, station.progress()) > maxDeviation) { + // Don't let the animation deviate too much from the reality + currentProgress = station.progress(); + } + + long intervalTime = (long) (station.progressToNext() / getMedianSpeed(currentStation)); // How many ms until it should reach the next station + double goalProgress = normalize(station.progress() + station.progressToNext()); // Where is the next station + double speed = normalize(goalProgress - currentProgress) / intervalTime; + + if (speed > MAX_SPEED) { + // Sanity check + currentProgress = stationDataMap.get(currentStation).progress(); + speed = getMedianSpeed(currentStation); + } + + positions.clear(); + positions.add(new Position(teamId, currentProgress, speed, timestamp)); + } + + public Position getPosition() { + if (!positions.isEmpty()) { + lastPosition = positions.poll(); + return lastPosition; + } + + return null; + } + + private boolean handleDetection(List newDetections) { + boolean newStation = false; + + newDetections.sort(Comparator.comparing(Detection::getTimestamp)); + for (Detection detection: newDetections) { + if (!detection.getTimestamp().after(detections.getLast().getTimestamp())) { + // Only keep newer detections + continue; + } + + detections.add(detection); // Newest detection is now at the end of the list + + if (detection.getStationId() == currentStation) { + // We've already determined that we have arrived at this station + continue; + } + + // Filter out old detections + long lastDetection = detections.getLast().getTimestamp().getTime(); + detections.removeIf(d -> lastDetection - d.getTimestamp().getTime() > INTERVAL); + + // Determine new position + int newStationId = detections.stream().max(Comparator.comparing(Detection::getRssi)).get().getStationId(); // detections will at least contain the last detection + if (currentStation != newStationId) { + // New position! + // Add new speed + if (currentStationDetection != null) { // Necessary for the first station switch + double progress = normalize(stationDataMap.get(newStationId).progress() - stationDataMap.get(currentStation).progress()); + double time = detection.getTimestamp().getTime() - currentStationDetection.getTimestamp().getTime(); + stationSpeeds.get(currentStation).add(progress / time); + } + + // Update station variables + currentStation = newStationId; + currentStationDetection = detection; + newStation = true; + } + } + + return newStation; + } + + private double getMedianSpeed(int stationId) { + List times = stationSpeeds.get(stationId); + if (times.size() > MAX_TIMES) { + times.subList(0, times.size() - MAX_TIMES).clear(); + } + + List copy = new ArrayList<>(times); + Collections.sort(copy); + + double median; + if (copy.size() % 2 == 0) { + median = (copy.get(copy.size() / 2) + copy.get(copy.size() / 2 - 1)) / 2; + } else { + median = copy.get(copy.size() / 2); + } + + return median; + } + + private double circularDistance(double a, double b) { + double diff = Math.abs(a - b); + return Math.min(diff, 1 - diff); + } + + private double normalize(double amount) { + return ((amount % 1) + 1) % 1; + } + +} From 9db9bbde9585bc4299745584d84d0363a1dc6896 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Fri, 11 Apr 2025 20:47:32 +0200 Subject: [PATCH 87/90] rip acceleration --- src/main/java/telraam/App.java | 2 +- .../telraam/logic/positioner/Position.java | 26 ------------------- .../nostradamus/v2/Nostradamus.java | 16 ++++++++---- .../nostradamus/v2/StationData.java | 6 ++--- .../nostradamus/v2/TeamHandler.java | 9 +++---- 5 files changed, 19 insertions(+), 40 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 92591df..1a1bdbf 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -144,8 +144,8 @@ public void run(AppConfiguration configuration, Environment environment) { Set positioners = new HashSet<>(); positioners.add(new Stationary(this.database)); - positioners.add(new Nostradamus(this.database)); positioners.add(new NostradamusV1(this.database)); + positioners.add(new Nostradamus(this.database)); // Start fetch thread for each station FetcherFactory fetcherFactory = new FetcherFactory(this.database, lappers, positioners); diff --git a/src/main/java/telraam/logic/positioner/Position.java b/src/main/java/telraam/logic/positioner/Position.java index 8d0d524..28a4e37 100644 --- a/src/main/java/telraam/logic/positioner/Position.java +++ b/src/main/java/telraam/logic/positioner/Position.java @@ -12,29 +12,3 @@ public record Position ( double speed, long timestamp ) {} -//public class Position { -// private final int teamId; -// private double progress; // Progress of the lap. Between 0-1 -// private double speed; // Current speed. progress / millisecond -// private long timestamp; // Timestamp in milliseconds -// -// public Position(int teamId) { -// this.teamId = teamId; -// this.progress = 0; -// this.speed = 0; -// this.timestamp = System.currentTimeMillis(); -// } -// -// public Position(int teamId, double progress) { -// this.teamId = teamId; -// this.progress = progress; -// this.speed = 0; -// this.timestamp = System.currentTimeMillis(); -// } -// -// public void update(double progress, double speed, long timestamp) { -// this.progress = progress; -// this.speed = speed; -// this.timestamp = timestamp; -// } -//} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java index 129c137..d47d3cf 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java @@ -18,16 +18,18 @@ public class Nostradamus implements Positioner { private static final Logger logger = Logger.getLogger(Nostradamus.class.getName()); - private final String SOURCE_NAME = "nostradamus_v2"; - private final int MIN_RSSI = -90; // Minimum rssi strength that a detections needs to have + private final String SOURCE_NAME = "nostradamus"; + private final int MIN_RSSI = -84; // Minimum rssi strength that a detections needs to have private final int INTERVAL_FETCH_MS = 10000; private final int INTERVAL_UPDATE_MS = 200; - private final int LENGTH_OFFSET = 10; // Distance from the last station to the finish in meter + private final int LENGTH_OFFSET = 40; // Distance from the last station to the finish in meter + private final double MAX_SPEED_M_MS = 0.00972222; // Maximum speed (m / ms) = 35 km / h private final Jdbi jdbi; private final PositionSender positionSender; ConcurrentHashMap> newDetections; private final Map teamHandlers; private final Map stationData; + private final double maxSpeedProgressMs; // Maximum speed (progress / ms) public Nostradamus(Jdbi jdbi) { this.jdbi = jdbi; @@ -55,9 +57,13 @@ public Nostradamus(Jdbi jdbi) { distanceToNext, station.getDistanceFromStart() / length, (double) distanceToNext / length, - stations.get(nextIdx).getId())); + stations.get(nextIdx).getId(), + i + )); } + this.maxSpeedProgressMs = MAX_SPEED_M_MS / (stations.get(stations.size() - 1).getDistanceFromStart() + LENGTH_OFFSET); + new Thread(this::fetch).start(); new Thread(this::update).start(); } @@ -78,7 +84,7 @@ private void fetch() { for (Map.Entry entry: batonToTeam.entrySet()) { teamHandlers.compute(entry.getValue(), (teamId, existingTeam) -> { if (existingTeam == null) { - return new TeamHandler(teamId, new AtomicInteger(entry.getKey()), stationData); + return new TeamHandler(teamId, new AtomicInteger(entry.getKey()), maxSpeedProgressMs, stationData); } else { existingTeam.batonId.set(entry.getKey()); return existingTeam; diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java index 442de6e..9f2b95d 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/StationData.java @@ -5,6 +5,6 @@ public record StationData( int distanceToNext, // Meters until the next station double progress, // Location of station in progress double progressToNext, // Progress until you arrive at the next station - int nextStationId // ID of the next station -) { -} + int nextStationId, // ID of the next station + int index // Index of the station when sorted by distance from the start +) {} diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java index 347d26b..2811d63 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java @@ -10,14 +10,12 @@ public class TeamHandler { private static final Logger logger = Logger.getLogger(TeamHandler.class.getName()); - // TODO: This won't be as effective for tracks with different lengths - private final double MAX_SPEED = 0.00003; // Max speed progress / ms private final double AVG_SPEED = 0.006; // Average sprinting speed (m / ms), results in a lap of 55 seconds in the 12ul private final int INTERVAL = 2000; // Only keep detections in a x ms interval private final int MAX_TIMES = 20; // Amount of speeds to keep track of to determine the median private final int teamId; public AtomicInteger batonId; - + private final double maxSpeed; private final Map stationDataMap; // Map from station id to StationData private final Map> stationSpeeds; // Avg speed (progress / ms) to go from a stationId to the next private int currentStation; // Current station id @@ -27,9 +25,10 @@ public class TeamHandler { private final LinkedList detections; private Detection currentStationDetection; - public TeamHandler(int teamId, AtomicInteger batonId, Map stationDataMap) { + public TeamHandler(int teamId, AtomicInteger batonId, double maxSpeed, Map stationDataMap) { this.teamId = teamId; this.batonId = batonId; + this.maxSpeed = maxSpeed; this.stationDataMap = stationDataMap; this.stationSpeeds = new HashMap<>(); @@ -70,7 +69,7 @@ public void update(List detections) { double goalProgress = normalize(station.progress() + station.progressToNext()); // Where is the next station double speed = normalize(goalProgress - currentProgress) / intervalTime; - if (speed > MAX_SPEED) { + if (speed > maxSpeed) { // Sanity check currentProgress = stationDataMap.get(currentStation).progress(); speed = getMedianSpeed(currentStation); From d00af2b323c349d7bbc7f83cd08d28736abe7f92 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Sun, 13 Apr 2025 23:21:25 +0200 Subject: [PATCH 88/90] refactor(detections): only store detections for which a baton is defined --- src/main/java/telraam/database/daos/DetectionDAO.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/database/daos/DetectionDAO.java b/src/main/java/telraam/database/daos/DetectionDAO.java index 4e45e3c..982b92c 100644 --- a/src/main/java/telraam/database/daos/DetectionDAO.java +++ b/src/main/java/telraam/database/daos/DetectionDAO.java @@ -34,8 +34,10 @@ INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id int insertAll(@BindBean List detection); @SqlBatch(""" - INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id, uptime_ms, timestamp_ingestion) \ - VALUES (:stationId, (SELECT id FROM baton WHERE mac = :batonMac), :timestamp, :rssi, :battery, :remoteId, :uptimeMs, :timestampIngestion) + INSERT INTO detection (station_id, baton_id, timestamp, rssi, battery, remote_id, uptime_ms, timestamp_ingestion) + SELECT :stationId, b.id, :timestamp, :rssi, :battery, :remoteId, :uptimeMs, :timestampIngestion + FROM baton b + WHERE b.mac = :batonMac """) @GetGeneratedKeys({"id", "baton_id"}) @RegisterBeanMapper(Detection.class) From 30d3935614e34af94f76757377ffdd69adbbe42e Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Tue, 1 Apr 2025 23:52:43 +0200 Subject: [PATCH 89/90] refactor(team): remove batonId & replace with view --- .../java/telraam/database/daos/TeamDAO.java | 8 ++--- .../V18__Remove_baton_id_from_teams.sql | 9 +++++ .../telraam/database/daos/TeamDAOTest.java | 33 +++++-------------- 3 files changed, 22 insertions(+), 28 deletions(-) create mode 100644 src/main/resources/db/migration/V18__Remove_baton_id_from_teams.sql diff --git a/src/main/java/telraam/database/daos/TeamDAO.java b/src/main/java/telraam/database/daos/TeamDAO.java index 77d8c84..a251884 100644 --- a/src/main/java/telraam/database/daos/TeamDAO.java +++ b/src/main/java/telraam/database/daos/TeamDAO.java @@ -14,17 +14,17 @@ public interface TeamDAO extends DAO { @Override - @SqlQuery("SELECT * FROM team") + @SqlQuery("SELECT t.*, tb.baton_id FROM team t LEFT JOIN team_baton_ids tb ON tb.team_id = t.id") @RegisterBeanMapper(Team.class) List getAll(); @Override - @SqlUpdate("INSERT INTO team (name, baton_id, jacket_nr) VALUES (:name, :batonId, :jacketNr)") + @SqlUpdate("INSERT INTO team (name, jacket_nr) VALUES (:name, :jacketNr)") @GetGeneratedKeys({"id"}) int insert(@BindBean Team team); @Override - @SqlQuery("SELECT * FROM team WHERE id = :id") + @SqlQuery("SELECT t.*, tb.baton_id FROM team t LEFT JOIN team_baton_ids tb ON tb.team_id = t.id WHERE t.id = :id") @RegisterBeanMapper(Team.class) Optional getById(@Bind("id") int id); @@ -33,6 +33,6 @@ public interface TeamDAO extends DAO { int deleteById(@Bind("id") int id); @Override - @SqlUpdate("UPDATE team SET name = :name, baton_id = :batonId, jacket_nr = :jacketNr WHERE id = :id") + @SqlUpdate("UPDATE team SET name = :name, jacket_nr = :jacketNr WHERE id = :id") int update(@Bind("id") int id, @BindBean Team modelObj); } diff --git a/src/main/resources/db/migration/V18__Remove_baton_id_from_teams.sql b/src/main/resources/db/migration/V18__Remove_baton_id_from_teams.sql new file mode 100644 index 0000000..0408a2f --- /dev/null +++ b/src/main/resources/db/migration/V18__Remove_baton_id_from_teams.sql @@ -0,0 +1,9 @@ +ALTER TABLE team DROP COLUMN baton_id; + +CREATE VIEW team_baton_ids (team_id, baton_id) +AS +SELECT bs.teamid, newbatonid +FROM batonswitchover bs + INNER JOIN (SELECT teamid, MAX(timestamp) AS max_timestamp + FROM batonswitchover + GROUP BY teamid) latest ON bs.teamid = latest.teamid AND bs.timestamp = latest.max_timestamp diff --git a/src/test/java/telraam/database/daos/TeamDAOTest.java b/src/test/java/telraam/database/daos/TeamDAOTest.java index 7dae6b7..16c6e0d 100644 --- a/src/test/java/telraam/database/daos/TeamDAOTest.java +++ b/src/test/java/telraam/database/daos/TeamDAOTest.java @@ -5,10 +5,13 @@ import org.junit.jupiter.api.Test; import telraam.DatabaseTest; import telraam.database.models.Baton; +import telraam.database.models.BatonSwitchover; import telraam.database.models.Team; import java.util.List; import java.util.Optional; +import java.sql.Timestamp; +import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.*; @@ -16,6 +19,7 @@ class TeamDAOTest extends DatabaseTest { private TeamDAO teamDAO; private BatonDAO batonDAO; + private BatonSwitchoverDAO batonSwitchoverDAO; @Override @BeforeEach @@ -23,6 +27,7 @@ public void setUp() throws Exception { super.setUp(); teamDAO = jdbi.onDemand(TeamDAO.class); batonDAO = jdbi.onDemand(BatonDAO.class); + batonSwitchoverDAO = jdbi.onDemand(BatonSwitchoverDAO.class); } @Test @@ -44,6 +49,10 @@ void testCreateTeamWithBaton() { Team testteam = new Team("testteam", batonId); int testId = teamDAO.insert(testteam); + LocalDateTime dateTime = LocalDateTime.now(); + BatonSwitchover switchover = new BatonSwitchover(testId, null, batonId, Timestamp.valueOf(dateTime)); + batonSwitchoverDAO.insert(switchover); + assertTrue(testId > 0); Optional teamOptional = teamDAO.getById(testId); assertFalse(teamOptional.isEmpty()); @@ -60,14 +69,6 @@ void testInsertFailsWhenNoName() { } - @Test - void testInsertFailsWhenInvalidBaton() { - Team testteam = new Team("testtteam", 1); - assertThrows(UnableToExecuteStatementException.class, - () -> teamDAO.insert(testteam)); - - } - @Test void testListTeamsEmpty() { List teams = teamDAO.getAll(); @@ -113,22 +114,6 @@ void testUpdateDoesUpdate() { assertEquals("10", dbTeam.get().getJacketNr()); } - @Test - void testUpdateFailsWhenInvalidBaton() { - Baton testBaton = new Baton("testbaton", "mac1"); - int batonId = batonDAO.insert(testBaton); - Team testTeam = new Team("testteam", batonId); - int teamId = teamDAO.insert(testTeam); - // TODO: this is a little awkward, monitor - // if this happens often in the real code - // and find a better way - testTeam.setId(teamId); - - testTeam.setBatonId(batonId + 1); - assertThrows(UnableToExecuteStatementException.class, - () -> teamDAO.update(teamId, testTeam)); - } - @Test void updateDoesntDoAnythingWhenNotExists() { Team testTeam = new Team("test"); From 982fa34eb937752bf95751f77c5e78f39d2b6948 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Tue, 15 Apr 2025 19:04:00 +0200 Subject: [PATCH 90/90] chore: cleanup --- src/main/java/telraam/App.java | 2 +- src/main/java/telraam/AppConfiguration.java | 6 ++++- .../nostradamus/v2/Nostradamus.java | 23 ++++++++++--------- .../nostradamus/v2/TeamHandler.java | 16 +++++++++---- src/main/resources/telraam/devConfig.yml | 3 +++ 5 files changed, 33 insertions(+), 17 deletions(-) diff --git a/src/main/java/telraam/App.java b/src/main/java/telraam/App.java index 1a1bdbf..7b8cc07 100644 --- a/src/main/java/telraam/App.java +++ b/src/main/java/telraam/App.java @@ -145,7 +145,7 @@ public void run(AppConfiguration configuration, Environment environment) { positioners.add(new Stationary(this.database)); positioners.add(new NostradamusV1(this.database)); - positioners.add(new Nostradamus(this.database)); + positioners.add(new Nostradamus(configuration, this.database)); // Start fetch thread for each station FetcherFactory fetcherFactory = new FetcherFactory(this.database, lappers, positioners); diff --git a/src/main/java/telraam/AppConfiguration.java b/src/main/java/telraam/AppConfiguration.java index c338c65..9648e63 100644 --- a/src/main/java/telraam/AppConfiguration.java +++ b/src/main/java/telraam/AppConfiguration.java @@ -8,7 +8,6 @@ import jakarta.validation.constraints.NotNull; import lombok.Getter; import lombok.Setter; -import telraam.api.responses.Template; public class AppConfiguration extends Configuration { @NotNull @@ -27,4 +26,9 @@ public class AppConfiguration extends Configuration { @Getter @Setter @JsonProperty("database") private DataSourceFactory dataSourceFactory = new DataSourceFactory(); + + @NotNull + @Getter + @JsonProperty("finish_offset") + private int finishOffset; } diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java index d47d3cf..05652ae 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/Nostradamus.java @@ -1,6 +1,7 @@ package telraam.logic.positioner.nostradamus.v2; import org.jdbi.v3.core.Jdbi; +import telraam.AppConfiguration; import telraam.database.daos.BatonSwitchoverDAO; import telraam.database.daos.PositionSourceDAO; import telraam.database.daos.StationDAO; @@ -22,7 +23,6 @@ public class Nostradamus implements Positioner { private final int MIN_RSSI = -84; // Minimum rssi strength that a detections needs to have private final int INTERVAL_FETCH_MS = 10000; private final int INTERVAL_UPDATE_MS = 200; - private final int LENGTH_OFFSET = 40; // Distance from the last station to the finish in meter private final double MAX_SPEED_M_MS = 0.00972222; // Maximum speed (m / ms) = 35 km / h private final Jdbi jdbi; private final PositionSender positionSender; @@ -31,7 +31,7 @@ public class Nostradamus implements Positioner { private final Map stationData; private final double maxSpeedProgressMs; // Maximum speed (progress / ms) - public Nostradamus(Jdbi jdbi) { + public Nostradamus(AppConfiguration configuration, Jdbi jdbi) { this.jdbi = jdbi; // Add as source @@ -48,7 +48,7 @@ public Nostradamus(Jdbi jdbi) { // Initialize station data list List stations = this.jdbi.onDemand(StationDAO.class).getAll(); stations.sort(Comparator.comparing(Station::getDistanceFromStart)); - int length = (int) (stations.get(stations.size() - 1).getDistanceFromStart() + LENGTH_OFFSET); + int length = (int) (stations.get(stations.size() - 1).getDistanceFromStart() + configuration.getFinishOffset()); for (int i = 0; i < stations.size(); i++) { Station station = stations.get(i); int nextIdx = (i + 1) % stations.size(); @@ -62,7 +62,7 @@ public Nostradamus(Jdbi jdbi) { )); } - this.maxSpeedProgressMs = MAX_SPEED_M_MS / (stations.get(stations.size() - 1).getDistanceFromStart() + LENGTH_OFFSET); + this.maxSpeedProgressMs = MAX_SPEED_M_MS / (stations.get(stations.size() - 1).getDistanceFromStart() + configuration.getFinishOffset()); new Thread(this::fetch).start(); new Thread(this::update).start(); @@ -73,13 +73,14 @@ private void fetch() { while (true) { List switchovers = jdbi.onDemand(BatonSwitchoverDAO.class).getAll(); - Map batonToTeam = switchovers.stream().sorted( - Comparator.comparing(BatonSwitchover::getTimestamp) - ).collect(Collectors.toMap( - BatonSwitchover::getNewBatonId, - BatonSwitchover::getTeamId, - (existing, replacement) -> replacement - )); + Map batonToTeam = switchovers.stream() + .filter(switchover -> switchover.getNewBatonId() != null) + .sorted(Comparator.comparing(BatonSwitchover::getTimestamp)) + .collect(Collectors.toMap( + BatonSwitchover::getNewBatonId, + BatonSwitchover::getTeamId, + (existing, replacement) -> replacement + )); for (Map.Entry entry: batonToTeam.entrySet()) { teamHandlers.compute(entry.getValue(), (teamId, existingTeam) -> { diff --git a/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java index 2811d63..c7e31de 100644 --- a/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java +++ b/src/main/java/telraam/logic/positioner/nostradamus/v2/TeamHandler.java @@ -21,7 +21,6 @@ public class TeamHandler { private int currentStation; // Current station id private Position lastPosition; private final Queue positions; - private final LinkedList detections; private Detection currentStationDetection; @@ -106,15 +105,15 @@ private boolean handleDetection(List newDetections) { } // Filter out old detections - long lastDetection = detections.getLast().getTimestamp().getTime(); + long lastDetection = detections.stream().max(Comparator.comparing(d -> d.getTimestamp().getTime())).get().getTimestamp().getTime(); detections.removeIf(d -> lastDetection - d.getTimestamp().getTime() > INTERVAL); // Determine new position int newStationId = detections.stream().max(Comparator.comparing(Detection::getRssi)).get().getStationId(); // detections will at least contain the last detection - if (currentStation != newStationId) { + if (currentStation != newStationId && stationAfter(newStationId)) { // New position! // Add new speed - if (currentStationDetection != null) { // Necessary for the first station switch + if (currentStationDetection != null && newStationId == stationDataMap.get(currentStation).nextStationId()) { // Necessary for the first station switch double progress = normalize(stationDataMap.get(newStationId).progress() - stationDataMap.get(currentStation).progress()); double time = detection.getTimestamp().getTime() - currentStationDetection.getTimestamp().getTime(); stationSpeeds.get(currentStation).add(progress / time); @@ -130,6 +129,15 @@ private boolean handleDetection(List newDetections) { return newStation; } + private boolean stationAfter(int newStationId) { + if (currentStationDetection == null) { + return true; + } + + int stations = stationDataMap.size(); + return (((stationDataMap.get(newStationId).index() - stationDataMap.get(currentStation).index()) % stations) + stations) % stations < 4; + } + private double getMedianSpeed(int stationId) { List times = stationSpeeds.get(stationId); if (times.size() > MAX_TIMES) { diff --git a/src/main/resources/telraam/devConfig.yml b/src/main/resources/telraam/devConfig.yml index f3b5a8f..db4adc8 100644 --- a/src/main/resources/telraam/devConfig.yml +++ b/src/main/resources/telraam/devConfig.yml @@ -46,6 +46,9 @@ database: # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction minIdleTime: 1 minute +# Distance between the start and the last station +finish_offset: 20 + # Logging settings. logging: