WebSocket
This commit is contained in:
1 parent
515f00b46f
commit
137a585edb
6 files changed
+210
-109
No files matched your search
@@ -98,6 +98,10 @@
|
|||||||
<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>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -1,75 +1,154 @@
|
|||||||
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.stereotype.Component;
|
||||||
import org.springframework.integration.annotation.ServiceActivator;
|
import org.springframework.web.socket.CloseStatus;
|
||||||
import org.springframework.integration.channel.DirectChannel;
|
import org.springframework.web.socket.TextMessage;
|
||||||
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
|
import org.springframework.web.socket.WebSocketSession;
|
||||||
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
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;
|
|
||||||
|
|
||||||
@Configuration
|
import jakarta.annotation.PostConstruct;
|
||||||
public class MqttConfig {
|
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_USER = "exodususer";
|
||||||
private static final String MQTT_PASSWORD = "awesomeexodusoutdooradventures";
|
private static final String MQTT_PASS = "awesomeexodusoutdooradventures";
|
||||||
|
|
||||||
@Bean
|
@PostConstruct
|
||||||
public MqttPahoClientFactory mqttClientFactory() {
|
public void initMqtt() {
|
||||||
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
|
try {
|
||||||
|
mqttClient = new MqttClient(BROKER_URL, MqttClient.generateClientId(), new MemoryPersistence());
|
||||||
MqttConnectOptions options = new MqttConnectOptions();
|
MqttConnectOptions options = new MqttConnectOptions();
|
||||||
options.setServerURIs(new String[] { BROKER_URL });
|
|
||||||
options.setUserName(MQTT_USER);
|
options.setUserName(MQTT_USER);
|
||||||
options.setPassword(MQTT_PASSWORD.toCharArray());
|
options.setPassword(MQTT_PASS.toCharArray());
|
||||||
|
options.setAutomaticReconnect(true);
|
||||||
options.setCleanSession(true);
|
options.setCleanSession(true);
|
||||||
factory.setConnectionOptions(options);
|
|
||||||
return factory;
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
public MessageChannel mqttOutboundChannel() {
|
public void connectionLost(Throwable cause) {
|
||||||
return new DirectChannel();
|
System.err.println("MQTT-Verbindung verloren: " + cause.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
@ServiceActivator(inputChannel = "mqttOutboundChannel")
|
public void messageArrived(String topic, MqttMessage message) {
|
||||||
public MessageHandler mqttOutbound() {
|
String payload = new String(message.getPayload());
|
||||||
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("springBootServerPublisher", mqttClientFactory());
|
broadcastToWebSockets(topic, payload);
|
||||||
messageHandler.setAsync(true);
|
|
||||||
messageHandler.setDefaultTopic("staging/outdoor/king-arthur/sword/set");
|
|
||||||
return messageHandler;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
public MessageChannel mqttInputChannel() {
|
public void deliveryComplete(IMqttDeliveryToken token) {}
|
||||||
return new DirectChannel();
|
});
|
||||||
|
|
||||||
|
mqttClient.connect(options);
|
||||||
|
} catch (MqttException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
public MqttPahoMessageDrivenChannelAdapter inbound() {
|
public void afterConnectionEstablished(WebSocketSession session) {
|
||||||
MqttPahoMessageDrivenChannelAdapter adapter =
|
// Da der Handshake erfolgreich war, ist der TourCode garantiert gültig
|
||||||
new MqttPahoMessageDrivenChannelAdapter("springBootServerSubscriber", mqttClientFactory(), "staging/outdoor/king-arthur/sword/stat");
|
sessions.add(session);
|
||||||
adapter.setCompletionTimeout(5000);
|
System.out.println("Client verbunden: " + session.getId() + " TourCode: " + session.getAttributes().get("tourCode"));
|
||||||
adapter.setConverter(new DefaultPahoMessageConverter());
|
|
||||||
adapter.setQos(2);
|
|
||||||
adapter.setOutputChannel(mqttInputChannel());
|
|
||||||
return adapter;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Override
|
||||||
@ServiceActivator(inputChannel = "mqttInputChannel")
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
||||||
public MessageHandler inboundHandler(SwordStateService swordStateService) {
|
try {
|
||||||
return message -> {
|
// Doppelte Absicherung im Handler
|
||||||
String payload = (String) message.getPayload();
|
if (session.getAttributes().get("tourCode") == null) {
|
||||||
System.out.println("Received MQTT payload: " + payload);
|
session.close(CloseStatus.NOT_ACCEPTABLE);
|
||||||
swordStateService.updateState(payload);
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||||
|
sessions.remove(session);
|
||||||
|
System.out.println("Client getrennt: " + session.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void broadcastToMqtt(String topic, String payload) {
|
||||||
|
// Interne Methode zum Broadcasten
|
||||||
|
}
|
||||||
|
|
||||||
|
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