我正在尝试使用MQTT以1秒的间隔将一些遥测值发布到物联网。
下面的以下Java代码在运行时有效,并反映在我的Thingsboard仪表板上。但是,当我尝试从另一个实例发布时(例如,使用mosquito命令行工具启动另一个实例),程序停止运行并在Java控制台中生成错误日志,指出“客户端未连接(32104)”
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MqttThingsBoard{
public static final ObjectMapper MAPPER = new ObjectMapper();
private String deviceToken;
private String clientId;
private MqttClientPersistence persistence;
private MqttAsyncClient client;
public MqttThingsBoard(String uri, String deviceToken) throws Exception {
this.clientId = MqttAsyncClient.generateClientId();
this.deviceToken = deviceToken;
this.persistence = new MemoryPersistence();
this.client = new MqttAsyncClient(uri, clientId, persistence);
}
public boolean connect() throws Exception {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(deviceToken);
try {
client.connect(options, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken iMqttToken) {
System.out.println(" Connected to Thingsboard!");
Runnable helloRunnable = new Runnable() {
public void run() {
try {
publishTelemetry(MAPPER.readTree("{\"temperature\": 10}"));
} catch (Exception e) {
e.printStackTrace();
}
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 1, TimeUnit.SECONDS);
}
@Override
public void onFailure(IMqttToken iMqttToken, Throwable e) {
System.out.println("Failed to connect to Thingsboard!");
}
}).waitForCompletion();
} catch (MqttException e) {
System.out.println("Failed to connect to the server");
}
return client.isConnected();
}
public void disconnect() throws Exception {
client.disconnect().waitForCompletion();
}
public void publishAttributes(JsonNode data) throws Exception {
publish("v1/devices/me/attributes", data);
}
public void publishTelemetry(JsonNode data) throws Exception {
publish("v1/devices/me/telemetry", data);
}
private void publish(String topic, JsonNode data) throws Exception {
MqttMessage msg = new MqttMessage(MAPPER.writeValueAsString(data).getBytes(StandardCharsets.UTF_8));
client.publish(topic, msg, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
System.out.println("Data updated!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
System.out.println("Data update failed!");
}
});
}
}