Files
ProcessControl/SIN.04028-From-Calling-to-Eventing/supplemental-java/06-mqtt/src/main/java/MqttConsoleIn.java
T

54 lines
1.5 KiB
Java

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import org.eclipse.paho.mqttv5.client.IMqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttMessage;
record ConsoleInMessage(String value) {}
void publish(
IMqttAsyncClient client,
String topic,
String content,
int qos,
boolean retained)
throws Exception {
var message = new MqttMessage(
content.getBytes(StandardCharsets.UTF_8)
);
message.setQos(qos);
message.setRetained(retained);
client.publish(topic, message).waitForCompletion();
}
void main(String[] arguments) throws Exception {
var unit = arguments.length == 0 ? "alice" : arguments[0];
var broker = System.getProperty("mqtt.broker", "tcp://localhost:1883");
var topic = "Tutorial/ConsoleIn/U/" + unit + "/E/text";
var client = new MqttAsyncClient(
broker,
"console-in-" + unit + "-" + UUID.randomUUID(),
new MemoryPersistence()
);
client.connect().waitForCompletion();
try {
while (true) {
var text = IO.readln();
if (text == null)
return;
var json = JsonTools.serializationObjectMapper
.writeValueAsString(new ConsoleInMessage(text));
publish(client, topic, json, 1, false);
}
} finally {
client.disconnect().waitForCompletion();
client.close();
}
}