Skip to content

Commit e6c78e9

Browse files
authored
Merge pull request eugenp#4832 from psevestre/master
Code for BAEL-1992
2 parents 7ff4d2e + a1d1d6b commit e6c78e9

4 files changed

Lines changed: 185 additions & 0 deletions

File tree

‎mqtt/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
### Relevant Articles:
2+
================================
3+
4+
- [MQTT Client in Java](http://www.baeldung.com/mqtt-client)

‎mqtt/pom.xml‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>org.baeldung</groupId>
5+
<artifactId>mqtt</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
8+
<parent>
9+
<groupId>com.baeldung</groupId>
10+
<artifactId>parent-modules</artifactId>
11+
<version>1.0.0-SNAPSHOT</version>
12+
</parent>
13+
14+
<dependencies>
15+
<dependency>
16+
<groupId>org.eclipse.paho</groupId>
17+
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
18+
<version>1.2.0</version>
19+
</dependency>
20+
</dependencies>
21+
22+
23+
</project>
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.mqtt;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.Callable;
5+
6+
import org.eclipse.paho.client.mqttv3.IMqttClient;
7+
import org.eclipse.paho.client.mqttv3.MqttMessage;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
public class EngineTemperatureSensor implements Callable<Void> {
12+
13+
private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class);
14+
public static final String TOPIC = "engine/temperature";
15+
16+
private IMqttClient client;
17+
private Random rnd = new Random();
18+
19+
public EngineTemperatureSensor(IMqttClient client) {
20+
this.client = client;
21+
}
22+
23+
@Override
24+
public Void call() throws Exception {
25+
26+
if ( !client.isConnected()) {
27+
log.info("[I31] Client not connected.");
28+
return null;
29+
}
30+
31+
MqttMessage msg = readEngineTemp();
32+
msg.setQos(0);
33+
msg.setRetained(true);
34+
client.publish(TOPIC,msg);
35+
36+
return null;
37+
}
38+
39+
/**
40+
* This method simulates reading the engine temperature
41+
* @return
42+
*/
43+
private MqttMessage readEngineTemp() {
44+
double temp = 80 + rnd.nextDouble() * 20.0;
45+
byte[] payload = String.format("T:%04.2f",temp).getBytes();
46+
MqttMessage msg = new MqttMessage(payload);
47+
return msg;
48+
}
49+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package com.baeldung.mqtt;
2+
3+
4+
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
6+
7+
import java.util.UUID;
8+
import java.util.concurrent.Callable;
9+
import java.util.concurrent.CountDownLatch;
10+
import java.util.concurrent.Executors;
11+
import java.util.concurrent.ScheduledExecutorService;
12+
import java.util.concurrent.TimeUnit;
13+
14+
import org.eclipse.paho.client.mqttv3.MqttClient;
15+
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
16+
import org.junit.Test;
17+
import org.slf4j.Logger;
18+
import org.slf4j.LoggerFactory;
19+
20+
public class EngineTemperatureSensorLiveTest {
21+
22+
private static Logger log = LoggerFactory.getLogger(EngineTemperatureSensorLiveTest.class);
23+
24+
@Test
25+
public void whenSendSingleMessage_thenSuccess() throws Exception {
26+
27+
String publisherId = UUID.randomUUID().toString();
28+
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
29+
30+
String subscriberId = UUID.randomUUID().toString();
31+
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
32+
33+
MqttConnectOptions options = new MqttConnectOptions();
34+
options.setAutomaticReconnect(true);
35+
options.setCleanSession(true);
36+
options.setConnectionTimeout(10);
37+
38+
39+
subscriber.connect(options);
40+
publisher.connect(options);
41+
42+
CountDownLatch receivedSignal = new CountDownLatch(1);
43+
44+
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
45+
byte[] payload = msg.getPayload();
46+
log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload));
47+
receivedSignal.countDown();
48+
});
49+
50+
51+
Callable<Void> target = new EngineTemperatureSensor(publisher);
52+
target.call();
53+
54+
receivedSignal.await(1, TimeUnit.MINUTES);
55+
56+
log.info("[I56] Success !");
57+
}
58+
59+
@Test
60+
public void whenSendMultipleMessages_thenSuccess() throws Exception {
61+
62+
String publisherId = UUID.randomUUID().toString();
63+
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
64+
65+
String subscriberId = UUID.randomUUID().toString();
66+
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
67+
68+
69+
MqttConnectOptions options = new MqttConnectOptions();
70+
options.setAutomaticReconnect(true);
71+
options.setCleanSession(true);
72+
options.setConnectionTimeout(10);
73+
74+
75+
publisher.connect(options);
76+
subscriber.connect(options);
77+
78+
CountDownLatch receivedSignal = new CountDownLatch(10);
79+
80+
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
81+
byte[] payload = msg.getPayload();
82+
log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload));
83+
receivedSignal.countDown();
84+
});
85+
86+
87+
Callable<Void> target = new EngineTemperatureSensor(publisher);
88+
89+
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
90+
executor.scheduleAtFixedRate(() -> {
91+
try {
92+
target.call();
93+
}
94+
catch(Exception ex) {
95+
throw new RuntimeException(ex);
96+
}
97+
}, 1, 1, TimeUnit.SECONDS);
98+
99+
100+
receivedSignal.await(1, TimeUnit.MINUTES);
101+
executor.shutdown();
102+
103+
assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero");
104+
105+
log.info("[I105] Success !");
106+
}
107+
108+
109+
}

0 commit comments

Comments
 (0)