Step By Step
1、创建实例
注意:整个实例的完整初始化大概需要10分钟左右。
2、切换实例(从共享实例切花到独享实例)
3、独享实例下面创建产品和设备(与共享实例操作方法一致)
4、获取连接参数
5、基于开源Java SDK上行数据
import com.alibaba.taro.AliyunIoTSignUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class IoTDemo1 {
public static String productKey = "g0fzs******";
public static String deviceName = "******";
public static String deviceSecret = "d2d447494a340499****************";
public static String regionId = "cn-shanghai";
public static String instanceId = "****************";
//物模型-属性上报topic
private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
private static MqttClient mqttClient;
public static void main(String [] args) throws MqttException {
initAliyunIoTClient();
ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());
scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 10,10, TimeUnit.SECONDS);
mqttClient.subscribe(subTopic);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("Topic : " + s);
System.out.println("message ;" + mqttMessage.getPayload());
System.out.println(new String(mqttMessage.getPayload())); //打印输出消息payLoad
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
private static void initAliyunIoTClient() {
try {
String clientId = "java" + System.currentTimeMillis();
Map<String, String> params = new HashMap<>(16);
params.put("productKey", productKey);
// params.put("IotInstanceId", instanceId);
params.put("deviceName", deviceName);
params.put("clientId", clientId);
String timestamp = String.valueOf(System.currentTimeMillis());
params.put("timestamp", timestamp);
String targetServer = "tcp://" + instanceId + ".mqtt.iothub.aliyuncs.com:1883";
String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
String mqttUsername = deviceName + "&" + productKey;
String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");
connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);
} catch (Exception e) {
System.out.println("initAliyunIoTClient error " + e.getMessage());
}
}
public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {
MemoryPersistence persistence = new MemoryPersistence();
mqttClient = new MqttClient(url, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
// MQTT 3.1.1
connOpts.setMqttVersion(4);
connOpts.setAutomaticReconnect(false);
connOpts.setCleanSession(true);
connOpts.setUserName(mqttUsername);
connOpts.setPassword(mqttPassword.toCharArray());
connOpts.setKeepAliveInterval(60);
mqttClient.connect(connOpts);
}
private static void postDeviceProperties() {
try {
//上报数据
//高级版 物模型-属性上报payload
String payloadJson = "{\"params\":{\"DetectDistance\":13}}";
MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
message.setQos(1);
mqttClient.publish(pubTopic, message);
System.out.println("upload message demo");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
7、设备上行消息,查询运行日志
可以基于日志,快速进行常见问题的排查定位。
8、使用SDK查看流转到TDSB的数据
- 8.1 pom.xml
<dependencies>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>hitsdb-client</artifactId>
<version>0.2.7</version>
</dependency>
</dependencies>
- 8.2 code sample
import com.aliyun.hitsdb.client.TSDB;
import com.aliyun.hitsdb.client.TSDBClientFactory;
import com.aliyun.hitsdb.client.TSDBConfig;
import com.aliyun.hitsdb.client.value.request.LastPointQuery;
import com.aliyun.hitsdb.client.value.request.LastPointSubQuery;
import com.aliyun.hitsdb.client.value.response.LastDataValue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class demo1 {
public static void main(String[] args) {
//实例详情页面中的连接地址、端口
String connectString = "************.hitsdb.rds.aliyuncs.com";
int port = 3242;
//实例详情页面中的时序数据存储用户名、密码
String username = "iot*****";
String password = "********";
TSDBConfig config = TSDBConfig.address(connectString, port)
.basicAuth(username, password)
// 网络连接池大小,默认为64。
.httpConnectionPool(64)
// HTTP 等待时间,单位为秒,默认为90秒。
.httpConnectTimeout(90)
// IO 线程数,默认为1。
.ioThreadCount(1)
.config();
TSDB tsdbClient = TSDBClientFactory.connect(config);
//按标签筛选数据
Map<String, String> tags = new HashMap<>();
tags.put("deviceName","device1");
String metric = "detectDistance";
long now = System.currentTimeMillis();
LastPointQuery query = LastPointQuery.builder()
.timestamp(now)
.backScan(-1)
.msResolution(true)
.sub(LastPointSubQuery.builder(metric, tags).build()).build();
List<LastDataValue> lastDataValues = tsdbClient.queryLast(query);
System.out.println(lastDataValues);
}
}
- 8.3 result
[LastDPValue [metric=detectDistance, timestamp=1594622426000, value=13.0, tags={deviceName=device1}, tsuid=0C000000000002000003000000000098]]