Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
210fdde27e | ||
|
|
0cd522acd8 | ||
|
|
801455dfcc | ||
|
|
fc77c7d8aa | ||
|
|
154cf7ce17 | ||
|
|
338714983d | ||
|
|
93b91c2c0f | ||
|
|
1e129d815a | ||
|
|
7ac7bfa2a8 | ||
|
|
137a585edb |
No files matched your search
@@ -10,7 +10,7 @@
|
||||
</parent>
|
||||
<groupId>de.exodus-hn</groupId>
|
||||
<artifactId>excalibur-tour</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>0.1.0</version>
|
||||
<name/>
|
||||
<description/>
|
||||
<url/>
|
||||
@@ -98,6 +98,10 @@
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -105,6 +109,13 @@
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<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.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@EnableScheduling
|
||||
@SpringBootApplication
|
||||
public class ExcaliburTourApplication {
|
||||
|
||||
|
||||
@@ -1,75 +1,177 @@
|
||||
package de.exodus_hn.excalibur_tour.configurations;
|
||||
|
||||
import de.exodus_hn.excalibur_tour.services.SwordStateService;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.integration.annotation.ServiceActivator;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
|
||||
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
|
||||
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
|
||||
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
|
||||
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
|
||||
import org.springframework.messaging.MessageChannel;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.paho.client.mqttv3.*;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||
|
||||
@Configuration
|
||||
public class MqttConfig {
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Component
|
||||
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();
|
||||
|
||||
private static final String BROKER_URL = "ssl://excaliburs-erben.de:8883";
|
||||
private static final String MQTT_USER = "exodususer";
|
||||
private static final String MQTT_PASSWORD = "awesomeexodusoutdooradventures";
|
||||
private static final String MQTT_PASS = "awesomeexodusoutdooradventures";
|
||||
|
||||
@Bean
|
||||
public MqttPahoClientFactory mqttClientFactory() {
|
||||
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
|
||||
MqttConnectOptions options = new MqttConnectOptions();
|
||||
options.setServerURIs(new String[] { BROKER_URL });
|
||||
options.setUserName(MQTT_USER);
|
||||
options.setPassword(MQTT_PASSWORD.toCharArray());
|
||||
options.setCleanSession(true);
|
||||
factory.setConnectionOptions(options);
|
||||
return factory;
|
||||
@Value("${testing.isMqttDev}")
|
||||
public boolean isDev;
|
||||
|
||||
@PostConstruct
|
||||
public void initMqtt() {
|
||||
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(String.valueOf(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());
|
||||
broadcastToWebSockets(topic, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {}
|
||||
});
|
||||
|
||||
mqttClient.connect(options);
|
||||
} catch (MqttException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel mqttOutboundChannel() {
|
||||
return new DirectChannel();
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) {
|
||||
// Da der Handshake erfolgreich war, ist der TourCode garantiert gültig
|
||||
sessions.add(session);
|
||||
logger.info("Client verbunden: " + session.getId() + " TourCode: " + session.getAttributes().get("tourCode"));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "mqttOutboundChannel")
|
||||
public MessageHandler mqttOutbound() {
|
||||
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("springBootServerPublisher", mqttClientFactory());
|
||||
messageHandler.setAsync(true);
|
||||
messageHandler.setDefaultTopic("staging/outdoor/king-arthur/sword/set");
|
||||
return messageHandler;
|
||||
@Override
|
||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
||||
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);
|
||||
|
||||
if (mqttClient != null && mqttClient.isConnected()) {
|
||||
MqttMessage mqttMessage = new MqttMessage(clientMsg.getPayload().getBytes());
|
||||
mqttMessage.setQos(2); // QoS = 2 für Steuerbefehle gemäß Spezifikation[cite: 7, 10]
|
||||
mqttClient.publish(clientMsg.getTopic(), mqttMessage);
|
||||
logger.fine("An MQTT gesendet [" + clientMsg.getTopic() + "]: " + clientMsg.getPayload());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageChannel mqttInputChannel() {
|
||||
return new DirectChannel();
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||
sessions.remove(session);
|
||||
logger.fine("Client getrennt: " + session.getId());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MqttPahoMessageDrivenChannelAdapter inbound() {
|
||||
MqttPahoMessageDrivenChannelAdapter adapter =
|
||||
new MqttPahoMessageDrivenChannelAdapter("springBootServerSubscriber", mqttClientFactory(), "staging/outdoor/king-arthur/sword/stat");
|
||||
adapter.setCompletionTimeout(5000);
|
||||
adapter.setConverter(new DefaultPahoMessageConverter());
|
||||
adapter.setQos(2);
|
||||
adapter.setOutputChannel(mqttInputChannel());
|
||||
return adapter;
|
||||
private void broadcastToMqtt(String topic, String payload) {
|
||||
// Interne Methode zum Broadcasten
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "mqttInputChannel")
|
||||
public MessageHandler inboundHandler(SwordStateService swordStateService) {
|
||||
return message -> {
|
||||
String payload = (String) message.getPayload();
|
||||
System.out.println("Received MQTT payload: " + payload);
|
||||
swordStateService.updateState(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; }
|
||||
}
|
||||
}
|
||||
+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 && 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;
|
||||
|
||||
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.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.TourSessionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Locale;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@CrossOrigin
|
||||
@RestController
|
||||
@@ -15,14 +25,24 @@ import java.time.temporal.ChronoUnit;
|
||||
@RequiredArgsConstructor
|
||||
public class CodeController {
|
||||
|
||||
private final Logger logger = Logger.getLogger("CodeController");
|
||||
|
||||
private final TourCodeService tourCodeService;
|
||||
private final TourSessionService tourSessionService;
|
||||
private final RiddleService riddleService;
|
||||
private final RiddleMapper riddleMapper;
|
||||
private final RandomStringUtils randomStringUtils = RandomStringUtils.secure();
|
||||
|
||||
@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);
|
||||
if (t == null) {
|
||||
t = tourCodeService.addTourCode(code);
|
||||
return "Created TC " + t.getId();
|
||||
/*t = tourCodeService.addTourCode(code);
|
||||
System.out.println("DEBUG: Created TC " + t.getId());*/
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
LocalDateTime now = Utils.getDateTimeNow();
|
||||
if (t.getActivated()) {
|
||||
@@ -30,18 +50,53 @@ public class CodeController {
|
||||
if (activationTimestamp == null) {
|
||||
t.setActivationTimestamp(now);
|
||||
tourCodeService.updateCode(t);
|
||||
} else if (activationTimestamp.plus(10, ChronoUnit.SECONDS).isBefore(now)) {
|
||||
return "Expired";
|
||||
} else if (activationTimestamp.plus(12, ChronoUnit.HOURS).isBefore(now)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
LocalDateTime heartbeat = t.getLastHeartbeatTimestamp();
|
||||
if (heartbeat != null && heartbeat.plus(2, ChronoUnit.SECONDS).isAfter(now)) {
|
||||
return "Expired (Wait a bit please)";
|
||||
if (heartbeat != null && heartbeat.plus(3, ChronoUnit.MINUTES).isAfter(now)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
t.setLastHeartbeatTimestamp(now);
|
||||
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);
|
||||
System.out.println("DEBUG: 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()) {
|
||||
System.out.println("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 failPenaltyPoints;
|
||||
private Integer skipPenaltyPoints;
|
||||
private Double requiredDistance;
|
||||
}
|
||||
@@ -48,6 +48,10 @@ public class ReadRiddleData {
|
||||
@JsonProperty(value = "skipPenaltyPoints", required = true)
|
||||
private Integer skipPenaltyPoints;
|
||||
|
||||
@NotNull
|
||||
@JsonProperty(value = "requiredDistance", required = true)
|
||||
private Double requiredDistance;
|
||||
|
||||
@NotNull
|
||||
@JsonProperty(value = "hints", required = true)
|
||||
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)
|
||||
private Integer skipPenaltyPoints;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Double requiredDistance;
|
||||
|
||||
@OneToMany(mappedBy = "riddle", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@Builder.Default
|
||||
private List<RiddleHint> hints = new ArrayList<>();
|
||||
|
||||
@@ -29,6 +29,11 @@ public class TourSession {
|
||||
@Column(name = "data", columnDefinition = "text")
|
||||
private String data;
|
||||
|
||||
public TourSession(String data, TourCode tourCode) {
|
||||
this.data = data;
|
||||
this.tourCode = tourCode;
|
||||
}
|
||||
|
||||
|
||||
/*@JdbcTypeCode(SqlTypes.JSON)
|
||||
@Column(name = "data", columnDefinition = "jsonb")
|
||||
|
||||
@@ -21,6 +21,7 @@ public interface RiddleMapper {
|
||||
.step(r.getStep())
|
||||
.failPenaltyPoints(r.getFailPenaltyPoints())
|
||||
.skipPenaltyPoints(r.getSkipPenaltyPoints())
|
||||
.requiredDistance(r.getRequiredDistance())
|
||||
.hints(r.getHints().stream().map(this::riddleHintToReadRiddleHint).toList())
|
||||
.build();
|
||||
}
|
||||
@@ -37,6 +38,7 @@ public interface RiddleMapper {
|
||||
.points(dto.getPoints())
|
||||
.failPenaltyPoints(dto.getFailPenaltyPoints())
|
||||
.skipPenaltyPoints(dto.getSkipPenaltyPoints())
|
||||
.requiredDistance(dto.getRequiredDistance())
|
||||
.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,65 @@
|
||||
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.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;
|
||||
|
||||
// Remembers the last state: true = gameStarted (players online), false = gameFinished (no one online)
|
||||
// Default to false (or true depending on initial assumption, false is safer on startup)
|
||||
private final AtomicBoolean lastStateWasActive = new AtomicBoolean(false);
|
||||
|
||||
@Value("${testing.isMqttDev}")
|
||||
public static boolean isDev;
|
||||
private static final String MQTT_TOPIC = (isDev ? "staging/" : "") + "outdoor/king-arthur/sword/set";
|
||||
|
||||
// Runs every 30 seconds (30000 milliseconds)
|
||||
@Scheduled(fixedRate = 30000)
|
||||
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));
|
||||
|
||||
// Check if state has changed
|
||||
boolean previousState = lastStateWasActive.get();
|
||||
if (anyCodeActive != previousState) {
|
||||
// State changed! Update memory state and send MQTT message
|
||||
lastStateWasActive.set(anyCodeActive);
|
||||
|
||||
if (anyCodeActive) {
|
||||
mqttConfig.publishMessage(MQTT_TOPIC, "gameStarted");
|
||||
logger.fine("Status geändert: Mindestens ein Code ist aktiv -> gameStarted gesendet.");
|
||||
} else {
|
||||
mqttConfig.publishMessage(MQTT_TOPIC, "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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TourCodeService {
|
||||
@@ -26,4 +28,8 @@ public class TourCodeService {
|
||||
public TourCode updateCode(TourCode 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);
|
||||
}
|
||||
}
|
||||
@@ -7,3 +7,5 @@ spring.datasource.username=root
|
||||
spring.datasource.password=EinPasswort
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
|
||||
|
||||
testing.isMqttDev=true
|
||||
Reference in new issue
Block a user