Added signal online indicator.

This commit is contained in:
Andrew Lalis 2021-11-23 10:49:07 +01:00
parent 591f46d60d
commit cbbf74ee4a
3 changed files with 27 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package nl.andrewl.railsignalapi.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Set;
@ -23,6 +24,10 @@ public class Signal {
@OneToMany(mappedBy = "signal", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<SignalBranchConnection> branchConnections;
@Column(nullable = false)
@Setter
private boolean online = false;
public Signal(RailSystem railSystem, String name, Set<SignalBranchConnection> branchConnections) {
this.railSystem = railSystem;
this.name = name;

View File

@ -9,7 +9,8 @@ import java.util.List;
public record SignalResponse(
long id,
String name,
List<ConnectionData> branchConnections
List<ConnectionData> branchConnections,
boolean online
) {
public SignalResponse(Signal signal) {
this(
@ -18,7 +19,8 @@ public record SignalResponse(
signal.getBranchConnections().stream()
.sorted(Comparator.comparing(SignalBranchConnection::getDirection))
.map(ConnectionData::new)
.toList()
.toList(),
signal.isOnline()
);
}

View File

@ -65,9 +65,15 @@ public class SignalService {
public void registerSignalWebSocketSession(Set<Long> signalIds, WebSocketSession session) {
this.signalWebSocketSessions.put(session, signalIds);
// Instantly send a data packet so that the signals are up-to-date.
RailSystem rs = null;
for (var signalId : signalIds) {
var signal = signalRepository.findById(signalId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid signal id."));
if (rs == null) {
rs = signal.getRailSystem();
} else if (!rs.getId().equals(signal.getRailSystem().getId())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot open signal websocket session for signals from different rail systems.");
}
for (var branchConnection : signal.getBranchConnections()) {
try {
session.sendMessage(new TextMessage(mapper.writeValueAsString(
@ -80,11 +86,22 @@ public class SignalService {
e.printStackTrace();
}
}
signal.setOnline(true);
signalRepository.save(signal);
}
}
@Transactional
public void deregisterSignalWebSocketSession(WebSocketSession session) {
this.signalWebSocketSessions.remove(session);
var ids = this.signalWebSocketSessions.remove(session);
if (ids != null) {
for (var signalId : ids) {
signalRepository.findById(signalId).ifPresent(signal -> {
signal.setOnline(false);
signalRepository.save(signal);
});
}
}
}
public WebSocketSession getSignalWebSocketSession(long signalId) {