使用mqttclient将设备数据发送到tb核心
package com.example;
import org.eclipse.paho.client.mqttv3.MqttClient;
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 java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class mqttMain {
public static void main(String[] args) throws MqttException {
String broker = "tcp://localhost:1883";
String clientId = "test123";
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("S1BiVGoEC9WKqiNiKva6");
//options.setCleanSession(true);
options.setKeepAliveInterval(1000);
MqttClient client = new MqttClient(broker, clientId);
client.connect(options);
if (client.isConnected()) {
System.out.println("连接成功");
String message = "{'temp':" + Math.random() * 100 + "}";
byte[] bytes = message.getBytes();
try {
client.publish("v1/devices/me/telemetry", bytes, 0, false);
} catch (MqttException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
ScheduledExecutorService service= Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable,10,1, TimeUnit.SECONDS);
}
}
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>