Compare commits
16
Commits
515f00b46f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccc011e142 | ||
|
|
fb37ba3b50 | ||
|
|
5bd9170800 | ||
|
|
eccb0efca3 | ||
|
|
00685ae103 | ||
|
|
e42b313640 | ||
|
|
210fdde27e | ||
|
|
0cd522acd8 | ||
|
|
801455dfcc | ||
|
|
fc77c7d8aa | ||
|
|
154cf7ce17 | ||
|
|
338714983d | ||
|
|
93b91c2c0f | ||
|
|
1e129d815a | ||
|
|
7ac7bfa2a8 | ||
|
|
137a585edb |
No files matched your search
@@ -10,7 +10,7 @@
|
|||||||
</parent>
|
</parent>
|
||||||
<groupId>de.exodus-hn</groupId>
|
<groupId>de.exodus-hn</groupId>
|
||||||
<artifactId>excalibur-tour</artifactId>
|
<artifactId>excalibur-tour</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.1.2</version>
|
||||||
<name/>
|
<name/>
|
||||||
<description/>
|
<description/>
|
||||||
<url/>
|
<url/>
|
||||||
@@ -29,6 +29,12 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<java.version>26</java.version>
|
<java.version>26</java.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>jitpack.io</id>
|
||||||
|
<url>https://jitpack.io</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
@@ -98,6 +104,15 @@
|
|||||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||||
<version>1.2.5</version>
|
<version>1.2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.serilogj</groupId>
|
||||||
|
<artifactId>serilogj</artifactId>
|
||||||
|
<version>0.6.1</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -105,6 +120,13 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package de.exodus_hn.excalibur_tour;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
|
@EnableScheduling
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class ExcaliburTourApplication {
|
public class ExcaliburTourApplication {
|
||||||
|
|
||||||
|
|||||||
@@ -1,75 +1,264 @@
|
|||||||
package de.exodus_hn.excalibur_tour.configurations;
|
package de.exodus_hn.excalibur_tour.configurations;
|
||||||
|
|
||||||
import de.exodus_hn.excalibur_tour.services.SwordStateService;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
import org.eclipse.paho.client.mqttv3.*;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.integration.annotation.ServiceActivator;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.integration.channel.DirectChannel;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
|
import org.springframework.web.socket.CloseStatus;
|
||||||
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
|
import org.springframework.web.socket.TextMessage;
|
||||||
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
|
import org.springframework.web.socket.WebSocketSession;
|
||||||
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
|
import jakarta.annotation.PostConstruct;
|
||||||
import org.springframework.messaging.MessageChannel;
|
import jakarta.annotation.PreDestroy;
|
||||||
import org.springframework.messaging.MessageHandler;
|
import java.io.IOException;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@Configuration
|
@Component
|
||||||
public class MqttConfig {
|
public class MqttConfig extends TextWebSocketHandler {
|
||||||
|
|
||||||
|
private final Logger logger = Logger.getLogger("MqttConfig");
|
||||||
|
|
||||||
|
private MqttClient mqttClient;
|
||||||
|
private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
|
// Atomic variable tracking whether the sword is online/active
|
||||||
|
public static final AtomicBoolean swordIsOnline = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
// Atomic variable tracking if a client already locked in onto the sword
|
||||||
|
private final AtomicBoolean swordLock = new AtomicBoolean(false);
|
||||||
|
private final AtomicReference<String> swordLockId = new AtomicReference<String>(null);
|
||||||
|
|
||||||
private static final String BROKER_URL = "ssl://excaliburs-erben.de:8883";
|
private static final String BROKER_URL = "ssl://excaliburs-erben.de:8883";
|
||||||
private static final String MQTT_USER = "exodususer";
|
private static final String MQTT_USER = "exodususer";
|
||||||
private static final String MQTT_PASSWORD = "awesomeexodusoutdooradventures";
|
private static final String MQTT_PASS = "awesomeexodusoutdooradventures";
|
||||||
|
|
||||||
@Bean
|
@Value("${testing.isMqttDev}")
|
||||||
public MqttPahoClientFactory mqttClientFactory() {
|
public boolean isDev;
|
||||||
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
|
|
||||||
MqttConnectOptions options = new MqttConnectOptions();
|
private final serilogj.core.Logger seqLogger;
|
||||||
options.setServerURIs(new String[] { BROKER_URL });
|
|
||||||
options.setUserName(MQTT_USER);
|
@Autowired
|
||||||
options.setPassword(MQTT_PASSWORD.toCharArray());
|
public MqttConfig(serilogj.core.Logger seqLogger) {
|
||||||
options.setCleanSession(true);
|
this.seqLogger = seqLogger;
|
||||||
factory.setConnectionOptions(options);
|
|
||||||
return factory;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@PostConstruct
|
||||||
public MessageChannel mqttOutboundChannel() {
|
public void initMqtt() {
|
||||||
return new DirectChannel();
|
try {
|
||||||
|
mqttClient = new MqttClient(BROKER_URL, MqttClient.generateClientId(), new MemoryPersistence());
|
||||||
|
MqttConnectOptions options = new MqttConnectOptions();
|
||||||
|
options.setUserName(MQTT_USER);
|
||||||
|
options.setPassword(MQTT_PASS.toCharArray());
|
||||||
|
options.setAutomaticReconnect(true);
|
||||||
|
options.setCleanSession(true);
|
||||||
|
|
||||||
|
mqttClient.setCallback(new MqttCallbackExtended() {
|
||||||
|
@Override
|
||||||
|
public void connectComplete(boolean reconnect, String serverURI) {
|
||||||
|
logger.info("MQTT in Dev-Mode: " + isDev);
|
||||||
|
logger.info(reconnect ? "Mit MQTT-Broker wiederverbunden." : "Mit MQTT-Broker verbunden.");
|
||||||
|
try {
|
||||||
|
// Alle Topics abonnieren
|
||||||
|
mqttClient.subscribe(isDev ? "staging/outdoor/king-arthur/#" : "outdoor/king-arthur/#", 2);
|
||||||
|
} catch (MqttException e) {
|
||||||
|
logger.throwing("MqttConfig.java", "initMqtt()V", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void connectionLost(Throwable cause) {
|
||||||
|
logger.severe("MQTT-Verbindung verloren: " + cause.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void messageArrived(String topic, MqttMessage message) {
|
||||||
|
String payload = new String(message.getPayload());
|
||||||
|
|
||||||
|
String eventTopic = (isDev ? "staging/" : "") + "outdoor/king-arthur/sword/event";
|
||||||
|
if (topic.equals(eventTopic)) {
|
||||||
|
if ("online".equalsIgnoreCase(payload) || "pong".equalsIgnoreCase(payload)) {
|
||||||
|
swordIsOnline.set(true);
|
||||||
|
seqLogger.information("[{Service}]: Got Sword {State}!", (isDev ? "Staging-" : "") + "Backend", "Online");
|
||||||
|
} else if ("offline".equalsIgnoreCase(payload)) {
|
||||||
|
swordIsOnline.set(false);
|
||||||
|
seqLogger.information("[{Service}]: Got Sword {State}!", (isDev ? "Staging-" : "") + "Backend", "Offline");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcastToWebSockets(topic, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deliveryComplete(IMqttDeliveryToken token) {}
|
||||||
|
});
|
||||||
|
|
||||||
|
mqttClient.connect(options);
|
||||||
|
} catch (MqttException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
@ServiceActivator(inputChannel = "mqttOutboundChannel")
|
public void afterConnectionEstablished(WebSocketSession session) {
|
||||||
public MessageHandler mqttOutbound() {
|
// Da der Handshake erfolgreich war, ist der TourCode garantiert gültig
|
||||||
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("springBootServerPublisher", mqttClientFactory());
|
sessions.add(session);
|
||||||
messageHandler.setAsync(true);
|
logger.info("Client verbunden: " + session.getId() + " TourCode: " + session.getAttributes().get("tourCode"));
|
||||||
messageHandler.setDefaultTopic("staging/outdoor/king-arthur/sword/set");
|
|
||||||
return messageHandler;
|
try {
|
||||||
|
String eventTopic = (isDev ? "staging/" : "") + "outdoor/king-arthur/sword/event";
|
||||||
|
String status = swordIsOnline.get() ? "online" : "offline";
|
||||||
|
String jsonMessage = objectMapper.writeValueAsString(new BridgeMessage(eventTopic, status));
|
||||||
|
String swordLockMessage = objectMapper.writeValueAsString(new BridgeMessage("system/swordLock", swordLock.get() ? "locked" : "unlocked"));
|
||||||
|
session.sendMessage(new TextMessage(jsonMessage));
|
||||||
|
session.sendMessage(new TextMessage(swordLockMessage));
|
||||||
|
logger.info("Client " + session.getId() + " den Status: " + status + " mitgeteilt. TourCode: " + session.getAttributes().get("tourCode"));
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.severe("Fehler beim Senden des aktuellen Sword-Status an neuen Client: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
public MessageChannel mqttInputChannel() {
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
||||||
return new DirectChannel();
|
try {
|
||||||
|
// Doppelte Absicherung im Handler
|
||||||
|
if (session.getAttributes().get("tourCode") == null) {
|
||||||
|
session.close(CloseStatus.NOT_ACCEPTABLE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientMessage clientMsg = objectMapper.readValue(message.getPayload(), ClientMessage.class);
|
||||||
|
|
||||||
|
logger.info(clientMsg.topic + ": " + clientMsg.payload);
|
||||||
|
|
||||||
|
if (clientMsg.topic.startsWith("system/")) {
|
||||||
|
if (clientMsg.topic.equals("system/swordLock")) {
|
||||||
|
if (clientMsg.payload.equals("takeLock")) {
|
||||||
|
logger.info(String.format("SID: %s LID: %s", session.getId(), swordLockId.get()));
|
||||||
|
if (swordLock.compareAndSet(false, true)) {
|
||||||
|
swordLockId.set(session.getId());
|
||||||
|
broadcastToWebSockets("system/swordLock", "locked");
|
||||||
|
seqLogger.information("[{Service}]: SwordMutexLock {LockState}", (isDev ? "Staging-" : "") + "Backend", "Locked");
|
||||||
|
}
|
||||||
|
} else if (clientMsg.payload.equals("giveLock")) {
|
||||||
|
logger.info(String.format("SID: %s LID: %s", session.getId(), swordLockId.get()));
|
||||||
|
if (session.getId().equals(swordLockId.get())) {
|
||||||
|
swordLock.set(false);
|
||||||
|
broadcastToWebSockets("system/swordLock", "unlocked");
|
||||||
|
seqLogger.information("[{Service}]: SwordMutexLock {LockState}", (isDev ? "Staging-" : "") + "Backend", "Unlocked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (mqttClient != null && mqttClient.isConnected()) {
|
||||||
|
MqttMessage mqttMessage = new MqttMessage(clientMsg.getPayload().getBytes());
|
||||||
|
mqttMessage.setQos(2);
|
||||||
|
mqttClient.publish(clientMsg.getTopic(), mqttMessage);
|
||||||
|
logger.fine("An MQTT gesendet [" + clientMsg.getTopic() + "]: " + clientMsg.getPayload());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
public MqttPahoMessageDrivenChannelAdapter inbound() {
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||||
MqttPahoMessageDrivenChannelAdapter adapter =
|
String swordlockid = swordLockId.get();
|
||||||
new MqttPahoMessageDrivenChannelAdapter("springBootServerSubscriber", mqttClientFactory(), "staging/outdoor/king-arthur/sword/stat");
|
String sessionId = session.getId();
|
||||||
adapter.setCompletionTimeout(5000);
|
logger.info(String.format("CLOSED: %s -> %s", sessionId, swordlockid));
|
||||||
adapter.setConverter(new DefaultPahoMessageConverter());
|
sessions.remove(session);
|
||||||
adapter.setQos(2);
|
if (swordlockid != null && swordlockid.equals(sessionId)) {
|
||||||
adapter.setOutputChannel(mqttInputChannel());
|
swordLock.set(false);
|
||||||
return adapter;
|
swordLockId.set(null);
|
||||||
|
broadcastToWebSockets("system/swordLock", "unlocked");
|
||||||
|
publishMessage((isDev ? "staging/" : "") + "outdoor/king-arthur/sword/set", "abortTry");
|
||||||
|
seqLogger.information("[{Service}]: SwordMutexLock {LockState} due to client disconnect", (isDev ? "Staging-" : "") + "Backend", "Unlocked");
|
||||||
|
seqLogger.fatal("[{Service}]: Sent abortTry due to client disconnect", (isDev ? "Staging-" : "") + "Backend");
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.fine("Client getrennt: " + session.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
@ServiceActivator(inputChannel = "mqttInputChannel")
|
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
|
||||||
public MessageHandler inboundHandler(SwordStateService swordStateService) {
|
String swordlockid = swordLockId.get();
|
||||||
return message -> {
|
String sessionId = session.getId();
|
||||||
String payload = (String) message.getPayload();
|
logger.info(String.format("ERROR: %s -> %s", sessionId, swordlockid));
|
||||||
System.out.println("Received MQTT payload: " + payload);
|
sessions.remove(session);
|
||||||
swordStateService.updateState(payload);
|
if (swordlockid != null && swordlockid.equals(sessionId)) {
|
||||||
};
|
swordLock.set(false);
|
||||||
|
swordLockId.set(null);
|
||||||
|
broadcastToWebSockets("system/swordLock", "unlocked");
|
||||||
|
seqLogger.information("[{Service}]: SwordMutexLock {LockState} due to client error", (isDev ? "Staging-" : "") + "Backend", "Unlocked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void broadcastToMqtt(String topic, String payload) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void broadcastToWebSockets(String topic, String payload) {
|
||||||
|
try {
|
||||||
|
String jsonMessage = objectMapper.writeValueAsString(new BridgeMessage(topic, payload));
|
||||||
|
TextMessage textMessage = new TextMessage(jsonMessage);
|
||||||
|
for (WebSocketSession session : sessions) {
|
||||||
|
if (session.isOpen()) {
|
||||||
|
session.sendMessage(textMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void cleanup() {
|
||||||
|
try {
|
||||||
|
if (mqttClient != null && mqttClient.isConnected()) {
|
||||||
|
mqttClient.disconnect();
|
||||||
|
}
|
||||||
|
} catch (MqttException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void publishMessage(String topic, String payload) {
|
||||||
|
try {
|
||||||
|
if (mqttClient != null && mqttClient.isConnected()) {
|
||||||
|
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
|
||||||
|
mqttMessage.setQos(2);
|
||||||
|
mqttClient.publish(topic, mqttMessage);
|
||||||
|
logger.info("An MQTT gesendet [" + topic + "]: " + payload);
|
||||||
|
} else {
|
||||||
|
logger.info("MQTT-Client ist nicht verbunden. Nachricht konnte nicht gesendet werden.");
|
||||||
|
}
|
||||||
|
} catch (MqttException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class BridgeMessage {
|
||||||
|
public String topic;
|
||||||
|
public String payload;
|
||||||
|
public BridgeMessage() {}
|
||||||
|
public BridgeMessage(String topic, String payload) {
|
||||||
|
this.topic = topic;
|
||||||
|
this.payload = payload;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ClientMessage {
|
||||||
|
private String topic;
|
||||||
|
private String payload;
|
||||||
|
public String getTopic() { return topic; }
|
||||||
|
public void setTopic(String topic) { this.topic = topic; }
|
||||||
|
public String getPayload() { return payload; }
|
||||||
|
public void setPayload(String payload) { this.payload = payload; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.configurations;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import serilogj.LoggerConfiguration;
|
||||||
|
import serilogj.events.LogEventLevel;
|
||||||
|
|
||||||
|
import static serilogj.sinks.coloredconsole.ColoredConsoleSinkConfigurator.coloredConsole;
|
||||||
|
import static serilogj.sinks.seq.SeqSinkConfigurator.seq;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SerilogjConfig {
|
||||||
|
|
||||||
|
@Value("${seq.server.url}")
|
||||||
|
private String seqUrl;
|
||||||
|
|
||||||
|
@Value("${seq.server.apiKey}")
|
||||||
|
private String seqApiKey;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public serilogj.core.Logger seqLogger() {
|
||||||
|
return new LoggerConfiguration()
|
||||||
|
.writeTo(coloredConsole())
|
||||||
|
.writeTo(seq(seqUrl, seqApiKey))
|
||||||
|
.setMinimumLevel(LogEventLevel.Verbose)
|
||||||
|
.createLogger();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.configurations;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.services.TourCodeService;
|
||||||
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
|
import org.springframework.http.server.ServletServerHttpRequest;
|
||||||
|
import org.springframework.web.socket.WebSocketHandler;
|
||||||
|
import org.springframework.web.socket.server.HandshakeInterceptor;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class TourCodeHandshakeInterceptor implements HandshakeInterceptor {
|
||||||
|
|
||||||
|
private final TourCodeService tourCodeService;
|
||||||
|
|
||||||
|
public TourCodeHandshakeInterceptor(TourCodeService tourCodeService) {
|
||||||
|
this.tourCodeService = tourCodeService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
|
||||||
|
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
|
||||||
|
if (request instanceof ServletServerHttpRequest) {
|
||||||
|
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
|
||||||
|
String tourCode = servletRequest.getServletRequest().getParameter("tourCode");
|
||||||
|
|
||||||
|
// Prüfen, ob der TourCode existiert und gültig ist
|
||||||
|
if (tourCode != null && (tourCode.equalsIgnoreCase("6MEGZDEI2") || tourCodeService.getTourCodeByCode(tourCode) != null)) {
|
||||||
|
// TourCode in den Session-Attributen für spätere Autorisierungen hinterlegen
|
||||||
|
attributes.put("tourCode", tourCode);
|
||||||
|
return true; // Verbindung erlauben
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false; // Verbindung ablehnen (Ungültiger oder fehlender TourCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
|
||||||
|
WebSocketHandler wsHandler, Exception exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.configurations;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.services.TourCodeService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||||
|
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||||
|
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSocket
|
||||||
|
public class WebSocketConfig implements WebSocketConfigurer {
|
||||||
|
|
||||||
|
private final MqttConfig mqttBridgeHandler;
|
||||||
|
private final TourCodeService tourCodeService;
|
||||||
|
|
||||||
|
public WebSocketConfig(MqttConfig mqttBridgeHandler, TourCodeService tourCodeService) {
|
||||||
|
this.mqttBridgeHandler = mqttBridgeHandler;
|
||||||
|
this.tourCodeService = tourCodeService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||||
|
registry.addHandler(mqttBridgeHandler, "/ws/bridge")
|
||||||
|
.addInterceptors(new TourCodeHandshakeInterceptor(tourCodeService))
|
||||||
|
.setAllowedOrigins("*"); // Adjust allowed origins for production
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,23 @@
|
|||||||
package de.exodus_hn.excalibur_tour.controller;
|
package de.exodus_hn.excalibur_tour.controller;
|
||||||
|
|
||||||
import de.exodus_hn.excalibur_tour.Utils;
|
import de.exodus_hn.excalibur_tour.Utils;
|
||||||
|
import de.exodus_hn.excalibur_tour.dto.riddle.ReadAllRiddleData;
|
||||||
|
import de.exodus_hn.excalibur_tour.dto.session.GetSessionAndAllRiddleData;
|
||||||
import de.exodus_hn.excalibur_tour.entities.TourCode;
|
import de.exodus_hn.excalibur_tour.entities.TourCode;
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourSession;
|
||||||
|
import de.exodus_hn.excalibur_tour.mapper.RiddleMapper;
|
||||||
|
import de.exodus_hn.excalibur_tour.services.RiddleService;
|
||||||
import de.exodus_hn.excalibur_tour.services.TourCodeService;
|
import de.exodus_hn.excalibur_tour.services.TourCodeService;
|
||||||
|
import de.exodus_hn.excalibur_tour.services.TourSessionService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@CrossOrigin
|
@CrossOrigin
|
||||||
@RestController
|
@RestController
|
||||||
@@ -15,14 +25,24 @@ import java.time.temporal.ChronoUnit;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class CodeController {
|
public class CodeController {
|
||||||
|
|
||||||
|
private final Logger logger = Logger.getLogger("CodeController");
|
||||||
|
|
||||||
private final TourCodeService tourCodeService;
|
private final TourCodeService tourCodeService;
|
||||||
|
private final TourSessionService tourSessionService;
|
||||||
|
private final RiddleService riddleService;
|
||||||
|
private final RiddleMapper riddleMapper;
|
||||||
|
private final RandomStringUtils randomStringUtils = RandomStringUtils.secure();
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public String test(@RequestParam(defaultValue = "ABCDEFGHI") String code) {
|
public ResponseEntity<GetSessionAndAllRiddleData> check(@RequestParam(required = true) String code) {
|
||||||
|
if (code == null || code.length() < 9) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
TourCode t = tourCodeService.getTourCodeByCode(code);
|
TourCode t = tourCodeService.getTourCodeByCode(code);
|
||||||
if (t == null) {
|
if (t == null) {
|
||||||
t = tourCodeService.addTourCode(code);
|
/*t = tourCodeService.addTourCode(code);
|
||||||
return "Created TC " + t.getId();
|
System.out.println("DEBUG: Created TC " + t.getId());*/
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
}
|
}
|
||||||
LocalDateTime now = Utils.getDateTimeNow();
|
LocalDateTime now = Utils.getDateTimeNow();
|
||||||
if (t.getActivated()) {
|
if (t.getActivated()) {
|
||||||
@@ -30,18 +50,55 @@ public class CodeController {
|
|||||||
if (activationTimestamp == null) {
|
if (activationTimestamp == null) {
|
||||||
t.setActivationTimestamp(now);
|
t.setActivationTimestamp(now);
|
||||||
tourCodeService.updateCode(t);
|
tourCodeService.updateCode(t);
|
||||||
} else if (activationTimestamp.plus(10, ChronoUnit.SECONDS).isBefore(now)) {
|
} else if (activationTimestamp.plus(12, ChronoUnit.HOURS).isBefore(now)) {
|
||||||
return "Expired";
|
logger.warning("Tour " + t.getCode() + " expired");
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
}
|
}
|
||||||
LocalDateTime heartbeat = t.getLastHeartbeatTimestamp();
|
LocalDateTime heartbeat = t.getLastHeartbeatTimestamp();
|
||||||
if (heartbeat != null && heartbeat.plus(2, ChronoUnit.SECONDS).isAfter(now)) {
|
if (heartbeat != null && heartbeat.plus(3, ChronoUnit.MINUTES).isAfter(now)) {
|
||||||
return "Expired (Wait a bit please)";
|
logger.warning("Tour " + t.getCode() + " was tried to be accessed.");
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
}
|
}
|
||||||
t.setLastHeartbeatTimestamp(now);
|
t.setLastHeartbeatTimestamp(now);
|
||||||
tourCodeService.updateCode(t);
|
tourCodeService.updateCode(t);
|
||||||
return "Have fun Ig";
|
TourSession tourSession = tourSessionService.getSessionByTourCode(t);
|
||||||
|
logger.info("Tour " + t.getCode() + " started playing with Session " + tourSession);
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
GetSessionAndAllRiddleData.builder()
|
||||||
|
.riddles(riddleService.getAllRiddles().stream()
|
||||||
|
.map(riddleMapper::riddleToReadRiddleData)
|
||||||
|
.toList())
|
||||||
|
.session(tourSession == null ? null : tourSession.getData()).build()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return "Expired (Disabled actually";
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<String> create(@RequestParam(required = false) String code) {
|
||||||
|
TourCode t = null;
|
||||||
|
if (code == null || code.length() < 9) {
|
||||||
|
boolean found = false;
|
||||||
|
for (int i = 0; i < 10; ++i) {
|
||||||
|
code = randomStringUtils.nextAlphanumeric(9).toUpperCase(Locale.ROOT);
|
||||||
|
t = tourCodeService.getTourCodeByCode(code);
|
||||||
|
if (t == null) {
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!found) {
|
||||||
|
return ResponseEntity.internalServerError().body("Couldn't create random code.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t = tourCodeService.getTourCodeByCode(code);
|
||||||
|
}
|
||||||
|
if (t == null) {
|
||||||
|
t = tourCodeService.addTourCode(code);
|
||||||
|
logger.info("Created TC " + t.getId());
|
||||||
|
return ResponseEntity.ok(t.getCode());
|
||||||
|
}
|
||||||
|
return ResponseEntity.badRequest().body("BAD: " + t.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.controller;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.Utils;
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourCode;
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourSession;
|
||||||
|
import de.exodus_hn.excalibur_tour.services.TourCodeService;
|
||||||
|
import de.exodus_hn.excalibur_tour.services.TourSessionService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.cglib.core.Local;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
@CrossOrigin
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/sessions")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SessionController {
|
||||||
|
|
||||||
|
private final Logger logger = Logger.getLogger("SessionController");
|
||||||
|
|
||||||
|
private final TourCodeService tourCodeService;
|
||||||
|
private final TourSessionService tourSessionService;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String getSession(@RequestParam(required = false) String code) {
|
||||||
|
if (code == null) {
|
||||||
|
return "No tour code given.";
|
||||||
|
}
|
||||||
|
TourSession session = tourSessionService.getSessionByTourCode(code);
|
||||||
|
if (session == null || !session.getTourCode().getActivated()) {
|
||||||
|
logger.info("Session not found for " + code);
|
||||||
|
return "Not available";
|
||||||
|
}
|
||||||
|
return String.format("%s", session.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<String> setSession(@RequestParam(required = true) String code, @RequestBody(required = true) String data) {
|
||||||
|
if (code == null) {
|
||||||
|
return ResponseEntity.badRequest().body("No Code");
|
||||||
|
}
|
||||||
|
TourCode tourCode = tourCodeService.getTourCodeByCode(code);
|
||||||
|
if (tourCode == null || !tourCode.getActivated()) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
LocalDateTime now = Utils.getDateTimeNow();
|
||||||
|
LocalDateTime activationTimestamp = tourCode.getActivationTimestamp();
|
||||||
|
if (activationTimestamp.plus(12, ChronoUnit.HOURS).isBefore(now)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
LocalDateTime heartbeat = tourCode.getLastHeartbeatTimestamp();
|
||||||
|
if (heartbeat != null && heartbeat.plus(3, ChronoUnit.MINUTES).isBefore(now)) {
|
||||||
|
return ResponseEntity.badRequest().body("Code invalid");
|
||||||
|
}
|
||||||
|
TourSession session = tourSessionService.getSessionByTourCode(code);
|
||||||
|
if (session == null) {
|
||||||
|
session = tourSessionService.addTourSession(data, tourCode);
|
||||||
|
} else {
|
||||||
|
session.setData(data);
|
||||||
|
session = tourSessionService.updateSession(session);
|
||||||
|
}
|
||||||
|
tourCode.setLastHeartbeatTimestamp(now);
|
||||||
|
tourCodeService.updateCode(tourCode);
|
||||||
|
logger.info("Tour: " + tourCode.getCode() + " updated Session!");
|
||||||
|
return ResponseEntity.ok(session.getId().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PatchMapping(path = "/finish")
|
||||||
|
public ResponseEntity<Void> markAsFinished(@RequestParam(required = true) String code) {
|
||||||
|
if (code == null) {
|
||||||
|
return ResponseEntity.badRequest().build();
|
||||||
|
}
|
||||||
|
TourCode t = tourCodeService.getTourCodeByCode(code);
|
||||||
|
if (t == null || !t.getActivated()) {
|
||||||
|
logger.warning(String.format("TourCode %s wurde nicht gefunden!", code));
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
t.setActivated(false);
|
||||||
|
tourCodeService.updateCode(t);
|
||||||
|
logger.info(String.format("TourCode %s wurde deaktiviert. (finish)", t.getCode()));
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
package de.exodus_hn.excalibur_tour.controller;
|
|
||||||
|
|
||||||
import de.exodus_hn.excalibur_tour.services.SwordStateService;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
|
||||||
import org.springframework.integration.support.MessageBuilder;
|
|
||||||
import org.springframework.integration.mqtt.support.MqttHeaders;
|
|
||||||
import org.springframework.messaging.Message;
|
|
||||||
import org.springframework.messaging.MessageChannel;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
@CrossOrigin
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/sword")
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class SwordController {
|
|
||||||
|
|
||||||
@Qualifier("mqttOutboundChannel")
|
|
||||||
private final MessageChannel mqttOutboundChannel;
|
|
||||||
|
|
||||||
private final SwordStateService swordStateService;
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public String getSwordState() {
|
|
||||||
return swordStateService.getCurrentState();
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/command/{commandType}")
|
|
||||||
public String sendCommand(@PathVariable String commandType) {
|
|
||||||
// Build and send the MQTT message directly to the channel[cite: 7]
|
|
||||||
Message<String> message = MessageBuilder.withPayload(commandType)
|
|
||||||
.setHeader(MqttHeaders.TOPIC, "staging/outdoor/king-arthur/sword/set")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
mqttOutboundChannel.send(message);
|
|
||||||
return "Command sent to MQTT: " + commandType;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,4 +17,5 @@ public class CreateRiddle {
|
|||||||
private Integer points;
|
private Integer points;
|
||||||
private Integer failPenaltyPoints;
|
private Integer failPenaltyPoints;
|
||||||
private Integer skipPenaltyPoints;
|
private Integer skipPenaltyPoints;
|
||||||
|
private Double requiredDistance;
|
||||||
}
|
}
|
||||||
@@ -48,6 +48,10 @@ public class ReadRiddleData {
|
|||||||
@JsonProperty(value = "skipPenaltyPoints", required = true)
|
@JsonProperty(value = "skipPenaltyPoints", required = true)
|
||||||
private Integer skipPenaltyPoints;
|
private Integer skipPenaltyPoints;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@JsonProperty(value = "requiredDistance", required = true)
|
||||||
|
private Double requiredDistance;
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@JsonProperty(value = "hints", required = true)
|
@JsonProperty(value = "hints", required = true)
|
||||||
private List<ReadRiddleHint> hints;
|
private List<ReadRiddleHint> hints;
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.dto.session;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import de.exodus_hn.excalibur_tour.dto.riddle.ReadAllRiddleData;
|
||||||
|
import de.exodus_hn.excalibur_tour.dto.riddle.ReadRiddleData;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class GetSessionAndAllRiddleData {
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@JsonProperty(value = "riddles", required = true)
|
||||||
|
private List<ReadRiddleData> riddles;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@JsonProperty(value = "session", required = true)
|
||||||
|
private String session;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -40,6 +40,9 @@ public class Riddle {
|
|||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
private Integer skipPenaltyPoints;
|
private Integer skipPenaltyPoints;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Double requiredDistance;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "riddle", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "riddle", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<RiddleHint> hints = new ArrayList<>();
|
private List<RiddleHint> hints = new ArrayList<>();
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ public class TourSession {
|
|||||||
@Column(name = "data", columnDefinition = "text")
|
@Column(name = "data", columnDefinition = "text")
|
||||||
private String data;
|
private String data;
|
||||||
|
|
||||||
|
public TourSession(String data, TourCode tourCode) {
|
||||||
|
this.data = data;
|
||||||
|
this.tourCode = tourCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/*@JdbcTypeCode(SqlTypes.JSON)
|
/*@JdbcTypeCode(SqlTypes.JSON)
|
||||||
@Column(name = "data", columnDefinition = "jsonb")
|
@Column(name = "data", columnDefinition = "jsonb")
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ public interface RiddleMapper {
|
|||||||
.step(r.getStep())
|
.step(r.getStep())
|
||||||
.failPenaltyPoints(r.getFailPenaltyPoints())
|
.failPenaltyPoints(r.getFailPenaltyPoints())
|
||||||
.skipPenaltyPoints(r.getSkipPenaltyPoints())
|
.skipPenaltyPoints(r.getSkipPenaltyPoints())
|
||||||
|
.requiredDistance(r.getRequiredDistance())
|
||||||
.hints(r.getHints().stream().map(this::riddleHintToReadRiddleHint).toList())
|
.hints(r.getHints().stream().map(this::riddleHintToReadRiddleHint).toList())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@ public interface RiddleMapper {
|
|||||||
.points(dto.getPoints())
|
.points(dto.getPoints())
|
||||||
.failPenaltyPoints(dto.getFailPenaltyPoints())
|
.failPenaltyPoints(dto.getFailPenaltyPoints())
|
||||||
.skipPenaltyPoints(dto.getSkipPenaltyPoints())
|
.skipPenaltyPoints(dto.getSkipPenaltyPoints())
|
||||||
|
.requiredDistance(dto.getRequiredDistance())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.repository;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourSession;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface TourSessionRepository extends JpaRepository<TourSession, Long> {
|
||||||
|
|
||||||
|
@Query("SELECT s FROM TourSession s JOIN s.tourCode c WHERE c.code = ?1")
|
||||||
|
Optional<TourSession> findByCode(String code);
|
||||||
|
|
||||||
|
@Query("SELECT s FROM TourSession s JOIN s.tourCode c WHERE c.id = ?1")
|
||||||
|
Optional<TourSession> findByTourCodeId(Long id);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.services;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.Utils;
|
||||||
|
import de.exodus_hn.excalibur_tour.configurations.MqttConfig;
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourCode;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class GameStatusMonitor {
|
||||||
|
|
||||||
|
private final Logger logger = Logger.getLogger("GameStatusMonitor");
|
||||||
|
|
||||||
|
private final TourCodeService tourCodeService;
|
||||||
|
private final MqttConfig mqttConfig;
|
||||||
|
|
||||||
|
private final AtomicBoolean lastStateWasActive = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private final serilogj.core.Logger seqLogger;
|
||||||
|
|
||||||
|
@Value("${testing.isMqttDev}")
|
||||||
|
public boolean isDev;
|
||||||
|
|
||||||
|
private String getMqttTopic() {
|
||||||
|
return (isDev ? "staging/" : "") + "outdoor/king-arthur/sword/set";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedRate = 15000)
|
||||||
|
public void checkActiveCodes() {
|
||||||
|
try {
|
||||||
|
List<TourCode> allCodes = tourCodeService.getAllTourCodes();
|
||||||
|
LocalDateTime now = Utils.getDateTimeNow();
|
||||||
|
|
||||||
|
boolean anyCodeActive = allCodes.stream()
|
||||||
|
.anyMatch(t -> Boolean.TRUE.equals(t.getActivated()) &&
|
||||||
|
t.getLastHeartbeatTimestamp() != null &&
|
||||||
|
t.getLastHeartbeatTimestamp().plus(3, ChronoUnit.MINUTES).isAfter(now));
|
||||||
|
|
||||||
|
boolean previousState = lastStateWasActive.get();
|
||||||
|
if (anyCodeActive != previousState) {
|
||||||
|
lastStateWasActive.set(anyCodeActive);
|
||||||
|
|
||||||
|
if (anyCodeActive) {
|
||||||
|
mqttConfig.publishMessage(getMqttTopic(), "gameStarted");
|
||||||
|
logger.fine("Status geändert: Mindestens ein Code ist aktiv -> gameStarted gesendet.");
|
||||||
|
} else {
|
||||||
|
mqttConfig.publishMessage(getMqttTopic(), "gameFinished");
|
||||||
|
logger.fine("Status geändert: Keine Codes mehr aktiv -> gameFinished gesendet.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.severe("Fehler beim Überprüfen des Spielstatus: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedRate = 60000)
|
||||||
|
public void pingOfflineSword() {
|
||||||
|
if (!MqttConfig.swordIsOnline.get()) {
|
||||||
|
mqttConfig.publishMessage(getMqttTopic(), "ping");
|
||||||
|
seqLogger.information("[{Service}] Pinging {Target}", (isDev ? "Staging-" : "") + "Backend-GameStatusMonitor", "Sword");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package de.exodus_hn.excalibur_tour.services;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class SwordStateService {
|
|
||||||
private final AtomicReference<String> currentState = new AtomicReference<>("No state received yet");
|
|
||||||
|
|
||||||
public void updateState(String state) {
|
|
||||||
currentState.set(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCurrentState() {
|
|
||||||
return currentState.get();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,6 +5,8 @@ import de.exodus_hn.excalibur_tour.repository.TourCodeRepository;
|
|||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class TourCodeService {
|
public class TourCodeService {
|
||||||
@@ -26,4 +28,8 @@ public class TourCodeService {
|
|||||||
public TourCode updateCode(TourCode tourCode) {
|
public TourCode updateCode(TourCode tourCode) {
|
||||||
return tourCodeRepository.save(tourCode);
|
return tourCodeRepository.save(tourCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<TourCode> getAllTourCodes() {
|
||||||
|
return tourCodeRepository.findAll();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package de.exodus_hn.excalibur_tour.services;
|
||||||
|
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourCode;
|
||||||
|
import de.exodus_hn.excalibur_tour.entities.TourSession;
|
||||||
|
import de.exodus_hn.excalibur_tour.repository.TourCodeRepository;
|
||||||
|
import de.exodus_hn.excalibur_tour.repository.TourSessionRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TourSessionService {
|
||||||
|
|
||||||
|
private final TourSessionRepository tourSessionRepository;
|
||||||
|
|
||||||
|
public TourSession getSessionByTourCode(String code) {
|
||||||
|
return tourSessionRepository.findByCode(code).orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TourSession getSessionByTourCode(TourCode tourCode) {
|
||||||
|
return tourSessionRepository.findByTourCodeId(tourCode.getId()).orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TourSession addTourSession(String data, TourCode tourCode) {
|
||||||
|
return tourSessionRepository.save(new TourSession(data, tourCode));
|
||||||
|
}
|
||||||
|
|
||||||
|
public TourSession updateSession(TourSession tourSession) {
|
||||||
|
return tourSessionRepository.save(tourSession);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,4 +6,6 @@ spring.datasource.url=jdbc:mariadb://${MYSQL_HOST:localhost}:3306/test
|
|||||||
spring.datasource.username=root
|
spring.datasource.username=root
|
||||||
spring.datasource.password=EinPasswort
|
spring.datasource.password=EinPasswort
|
||||||
spring.jpa.hibernate.ddl-auto=update
|
spring.jpa.hibernate.ddl-auto=update
|
||||||
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
|
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
|
||||||
|
|
||||||
|
testing.isMqttDev=true
|
||||||
Reference in new issue
Block a user