阿里云物联网平台独享实例使用Quick Start-阿里云开发者社区

开发者社区> 阿里云物联网> 正文

阿里云物联网平台独享实例使用Quick Start

简介: 目前物联网平台有两类实例:公共实例和用户购买的实例。相较共享实例,独享实例提供时序数据存储,用于根据设备数据进行业务分析和监控,购买的实例与其他实例之间相隔离,具有更高的数据可靠性和安全性。本文主要介绍独享实例的快速使用Quick Start。

Step By Step

1、创建实例
图片.png

注意:整个实例的完整初始化大概需要10分钟左右。

2、切换实例(从共享实例切花到独享实例)
图片.png

3、独享实例下面创建产品和设备(与共享实例操作方法一致)
图片.png

4、获取连接参数
图片.png

图片.png

图片.png

5、基于开源Java SDK上行数据

参考链接:基于开源JAVA MQTT Client连接阿里云IoT

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());
        }
    }
}

6、数据转发到实例内的时序数据存储
图片.png

7、设备上行消息,查询运行日志

可以基于日志,快速进行常见问题的排查定位。

图片.png

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]]

更多参考

实例管理
基于开源JAVA MQTT Client连接阿里云IoT
阿里云物联网平台博客综述

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
阿里云物联网
使用钉钉扫一扫加入圈子
+ 订阅

致力于实现万物互联的美好世界,为生态合作伙伴提供基于云计算、大数据、人工智能、云端一体化、安全的物联网基础平台和内容服务平台。

官方博客
物联网相关产品售前咨询
开发者交流群