-
Notifications
You must be signed in to change notification settings - Fork 14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds basic MQTT support with remote events #1509
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
* The MIT License | ||
* | ||
* Copyright 2023-2023 TweetWallFX | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
|
||
dependencies { | ||
implementation project(':tweetwallfx-configuration') | ||
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' | ||
implementation 'org.slf4j:slf4j-api:2.0.6' | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
/* | ||
* The MIT License (MIT) | ||
* | ||
* Copyright (c) 2023 TweetWallFX | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
package org.tweetwallfx.mqtt; | ||
|
||
import javafx.event.Event; | ||
import javafx.event.EventType; | ||
|
||
public class MqttEvent extends Event { | ||
public static final EventType<MqttEvent> ANY = new EventType<>(Event.ANY, "ANY"); | ||
public static final EventType<MqttEvent> RESTART = new EventType<>(Event.ANY, "RESTART"); | ||
public static final EventType<MqttEvent> STOP = new EventType<>(Event.ANY, "STOP"); | ||
|
||
public MqttEvent(Object source, EventType<? extends Event> eventType) { | ||
super(source, null, eventType); | ||
} | ||
} |
181 changes: 181 additions & 0 deletions
181
mqtt/src/main/java/org/tweetwallfx/mqtt/MqttProcess.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
/* | ||
* The MIT License (MIT) | ||
* | ||
* Copyright (c) 2023 TweetWallFX | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
package org.tweetwallfx.mqtt; | ||
|
||
import javafx.beans.property.BooleanProperty; | ||
import javafx.beans.property.ReadOnlyBooleanProperty; | ||
import javafx.beans.property.SimpleBooleanProperty; | ||
import javafx.event.EventHandler; | ||
import org.eclipse.paho.client.mqttv3.MqttClient; | ||
import org.eclipse.paho.client.mqttv3.MqttClientPersistence; | ||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; | ||
import org.eclipse.paho.client.mqttv3.MqttException; | ||
import org.eclipse.paho.client.mqttv3.MqttMessage; | ||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.tweetwallfx.config.Configuration; | ||
import org.tweetwallfx.mqtt.config.MqttSettings; | ||
|
||
import java.io.UncheckedIOException; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Objects; | ||
import java.util.Optional; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicReference; | ||
|
||
import static java.util.concurrent.TimeUnit.MILLISECONDS; | ||
import static org.tweetwallfx.util.JsonDataConverter.convertToBytes; | ||
|
||
public class MqttProcess implements Runnable { | ||
private static final String TWEETWALL_STATE = "tweetwall/state/"; | ||
private static final Logger LOG = LoggerFactory.getLogger(MqttProcess.class); | ||
|
||
private final BooleanProperty stopProperty = new SimpleBooleanProperty(); | ||
private final BooleanProperty runningProperty = new SimpleBooleanProperty(); | ||
private final List<EventHandler<MqttEvent>> handlers = new ArrayList<>(); | ||
private final AtomicReference<MqttClient> clientRef = new AtomicReference<>(); | ||
|
||
private void fire(MqttEvent mqttEvent) { | ||
handlers.forEach(h -> h.handle(mqttEvent)); | ||
} | ||
|
||
public void addMqttEventHandler(EventHandler<MqttEvent> handler) { | ||
handlers.add(Objects.requireNonNull(handler)); | ||
} | ||
|
||
public ReadOnlyBooleanProperty runningProperty() { | ||
return ReadOnlyBooleanProperty.readOnlyBooleanProperty(runningProperty); | ||
} | ||
|
||
public void stop() { | ||
stopProperty.set(true); | ||
while (runningProperty.get()) { | ||
waitFor(MILLISECONDS, 500); | ||
} | ||
} | ||
|
||
@Override | ||
public void run() { | ||
try { | ||
Thread.currentThread().setName("MQTT-Command-Dispatcher"); | ||
final MqttSettings mqttSettings = Configuration.getInstance() | ||
.getConfigTyped(MqttSettings.CONFIG_KEY, MqttSettings.class); | ||
if (!mqttSettings.enabled()) { | ||
LOG.info("MQTT disabled"); | ||
return; | ||
} | ||
long lastHeartbeat = 0; | ||
while (!stopProperty.get()) { | ||
final String broker = mqttSettings.brokerUrl(); | ||
final String clientId = mqttSettings.clientId(); | ||
try (MqttClientPersistence persistence = new MemoryPersistence(); | ||
MqttClient mqttClient = new MqttClient(broker, clientId, persistence)) { | ||
clientRef.set(mqttClient); | ||
MqttConnectOptions connOpts = new MqttConnectOptions(); | ||
connOpts.setCleanSession(true); | ||
connOpts.setConnectionTimeout(0); | ||
connOpts.setKeepAliveInterval(30); | ||
connOpts.setAutomaticReconnect(true); | ||
final MqttSettings.Auth auth = mqttSettings.auth(); | ||
Optional.ofNullable(auth.userName()).ifPresent(connOpts::setUserName); | ||
Optional.ofNullable(auth.secret()).ifPresent(pw -> connOpts.setPassword(pw.toCharArray())); | ||
LOG.info("Connect to {}", broker); | ||
mqttClient.connect(connOpts); | ||
stopProperty.addListener((observableValue, oldValue, newValue) -> { | ||
if (newValue) { | ||
sendMessage(TWEETWALL_STATE, State.stopping()); | ||
try { | ||
LOG.info("Disconnecting"); | ||
mqttClient.disconnect(); | ||
} catch (MqttException e) { | ||
LOG.error("Failed to send stop notification", e); | ||
} | ||
} | ||
}); | ||
runningProperty.set(true); | ||
sendMessage(TWEETWALL_STATE, State.starting(SystemInfo.info())); | ||
LOG.info("Connection established"); | ||
mqttClient.subscribe("tweetwall/action/#", (t, m) -> handleActionMessage(clientId, t, m)); | ||
while (!stopProperty.get()) { | ||
// heart beat task | ||
long currentTime = System.currentTimeMillis(); | ||
long duration = MILLISECONDS.toSeconds(currentTime - lastHeartbeat); | ||
if (duration >= mqttSettings.heartbeatSeconds()) { | ||
lastHeartbeat = currentTime; | ||
LOG.debug("Sending heart beat message"); | ||
sendMessage(TWEETWALL_STATE, State.alive()); | ||
} else { | ||
waitFor(MILLISECONDS, 500); | ||
} | ||
} | ||
} catch (MqttException e) { | ||
LOG.error("Failure while handling MQTT", e); | ||
} finally { | ||
clientRef.set(null); | ||
} | ||
} | ||
} finally { | ||
runningProperty.set(false); | ||
} | ||
} | ||
|
||
private static void waitFor(TimeUnit unit, long amount) { | ||
try { | ||
unit.sleep(amount); | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
LOG.error("Interrupted while waiting", e); | ||
} | ||
} | ||
|
||
private void handleActionMessage(String clientId, String topic, MqttMessage message) { | ||
String payload = new String(message.getPayload(), StandardCharsets.UTF_8); | ||
if (topic.equals("tweetwall/action/" + clientId)) { | ||
switch (payload) { | ||
case "stop" -> fire(new MqttEvent(this, MqttEvent.STOP)); | ||
case "restart" -> fire(new MqttEvent(this, MqttEvent.RESTART)); | ||
case "info" -> sendMessage(TWEETWALL_STATE, State.info(SystemInfo.info())); | ||
default -> LOG.warn("Unknown action payload: {}", payload); | ||
} | ||
} else { | ||
LOG.warn("Unknown payload '{}' for topic {}", payload, topic); | ||
} | ||
} | ||
|
||
private void sendMessage(String topic, Object messageObject) { | ||
final MqttClient mqttClient = clientRef.get(); | ||
if (mqttClient == null) { | ||
LOG.error("Failed to send '{}' for topic {} as no client available", messageObject, topic); | ||
} else { | ||
try { | ||
mqttClient.publish(topic + mqttClient.getClientId(), convertToBytes(messageObject), 2, false); | ||
} catch (MqttException | UncheckedIOException e) { | ||
LOG.error("Failed to send '{}' for topic {}", messageObject, topic, e); | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not strictly required at the moment as the rootProject adds it as implementation dependency to every leaf project. not bad per se...