WebSocket
This commit is contained in:
1 parent
515f00b46f
commit
137a585edb
6 files changed
+213
-112
No files matched your search
@@ -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>
|
||||
|
||||
@@ -1,75 +1,154 @@
|
||||
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.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;
|
||||
|
||||
private static final String BROKER_URL = "ssl://excaliburs-erben.de:8883";
|
||||
@Component
|
||||
public class MqttConfig extends TextWebSocketHandler {
|
||||
|
||||
private MqttClient mqttClient;
|
||||
private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private static final String BROKER_URL = "ssl://nerdyssey.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;
|
||||
@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) {
|
||||
System.out.println("Mit MQTT-Broker verbunden. Reconnect: " + reconnect);
|
||||
try {
|
||||
// Alle King Arthur IoT-Topics abonnieren
|
||||
mqttClient.subscribe("outdoor/king-arthur/#", 2);
|
||||
} catch (MqttException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
System.err.println("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);
|
||||
System.out.println("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);
|
||||
System.out.println("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);
|
||||
System.out.println("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 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; }
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
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.equals("TESTTEST!")) {
|
||||
attributes.put("tourCode", tourCode);
|
||||
return true;
|
||||
}
|
||||
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,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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user