阿里云物联网平台设备分发实战

简介: 物联网平台通过设备分发实现设备跨地域、跨实例或跨账号的分发。分发后,物联网平台下发新的连接地址给设备,设备本地固化收到信息之后,直接连接新的地址,免去二次烧录设备信息。本文主要演示指定地域的分发方式,设备完成分发后,通过向认证中心请求新的连接地址,重新建立连接。

一、源实例创建产品和设备

  • 1.1 登录物联网平台控制台,选择实例进入

图片.png

  • 1.2 创建产品和设备

图片.png

图片.png

图片.png

  • 1.3 Java MQTT连接设备
源码参考: 基于开源JAVA MQTT Client连接阿里云IoT

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import 一机一密.AliyunIoTSignUtil;

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 shebenbufenfa {

    public static String productKey = "******";
    public static String deviceName = "sourcedevice1";
    public static String deviceSecret = "******";
    public static String instanceId = "iot-******";

    // 物模型-属性上报topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
    // 物模型-属性响应topic
    private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
    private static MqttClient mqttClient;

    public static void main(String [] args){

        initAliyunIoTClient();
        ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());

        scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 2,2, TimeUnit.SECONDS);

        try {
            mqttClient.subscribe(subTopic); // 订阅Topic
        } catch (MqttException e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }

        // 设置订阅监听
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connection Lost");
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("Sub message");
                System.out.println("Topic : " + s);
                System.out.println("message info " + new String(mqttMessage.getPayload())); //打印输出消息payLoad
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                try {
                    System.out.println("deliveryComplete: " + iMqttDeliveryToken.getMessage());
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化 Client 对象
     */
    private static void initAliyunIoTClient() {

        try {
            // 构造连接需要的参数
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            // cn-shanghai
            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.setConnectionTimeout(10);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
    }

    /**
     * 汇报属性
     */
    private static void postDeviceProperties() {

        try {
            //上报数据
            //高级版 物模型-属性上报payload
            System.out.println("上报属性值");
            // 基于产品物模型定义设置
            String payloadJson = "{\"params\":{\"LightStatus\":1,\"LightAdjustLevel\":15}}";
            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
  • 1.4 查看设备在线及数据上报情况

图片.png

二、设备分发(指定地域)

  • 2.1 设备划归 -> 设备分发

图片.png

  • 2.2 目标账户查看

图片.png

请求物联网平台Server,获取新的设备认证地址

可以基于官方SDK使用其:Bootstrap功能开发的具体操作,请参见概述。这里介绍使用okhttp自行接入方式接入
  • 3.1 pom.xml
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.4.1</version>
        </dependency>
  • 3.2 Code Sample
import okhttp3.*;
import java.io.IOException;

public class demo1 {

    public static void main(String[] args) throws IOException {

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType =MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType,"productKey=hz56a******&deviceName=sourced*****&clientId=taroclient1&version=v2&timestamp=1669267341");

        Request request = new Request.Builder()
                .url("https://iot-auth-global.aliyuncs.com/auth/bootstrap/")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}
  • 3.3 返回结果

{"code":200,"data":{"instanceId":"iotx-oxss********","resources":{"mqtt":{"host":"public.iot-as-mqtt.cn-shanghai.aliyuncs.com","ip":"139.224.42.2","port":1883}}},"message":"success"}
设备分发到新的用户或者实例后,设备三元组信息不变,仅连接域名会发生变化,连接域名修改为上面请求获取的域名即可。
  • 3.4 划归后的设备测试情况

图片.png

更多参考

使用okhttp时没有返回正常数据
设备分发
Can't get OkHttp's response.body.toString() to return a string

相关实践学习
阿里云AIoT物联网开发实战
本课程将由物联网专家带你熟悉阿里云AIoT物联网领域全套云产品,7天轻松搭建基于Arduino的端到端物联网场景应用。 开始学习前,请先开通下方两个云产品,让学习更流畅: IoT物联网平台:https://iot.console.aliyun.com/ LinkWAN物联网络管理平台:https://linkwan.console.aliyun.com/service-open
相关文章
|
2月前
|
消息中间件 安全 物联网
海量接入、毫秒响应:易易互联携手阿里云构筑高可用物联网消息中枢
面对换电生态高速发展的通信挑战,易易互联通过采用阿里云 MQTT + RocketMQ 的融合解决方案,成功构建了“海量接入、实时响应、弹性处理、安全可信”的物联网通信底座。该架构不仅显著提升了系统稳定性与可扩展性,更保障了高并发场景下的业务连续性,为实现“让换电成为营运补能第一选择”的战略目标提供了坚实的技术支撑。
184 31
|
8月前
|
传感器 人工智能 物联网
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
1013 19
|
6月前
|
物联网
(手把手)在华为云、阿里云搭建自己的物联网MQTT消息服务器,免费IOT平台
本文介绍如何在阿里云搭建自己的物联网MQTT消息服务器,并使用 “MQTT客户端调试工具”模拟MQTT设备,接入平台进行消息收发。
2232 42
|
6月前
|
运维 监控 网络协议
物联网设备状态监控全解析:从告警参数到静默管理的深度指南-优雅草卓伊凡
物联网设备状态监控全解析:从告警参数到静默管理的深度指南-优雅草卓伊凡
193 11
物联网设备状态监控全解析:从告警参数到静默管理的深度指南-优雅草卓伊凡
|
6月前
|
机器学习/深度学习 人工智能 运维
星云智控自定义物联网实时监控模板-为何成为痛点?物联网设备的多样化-优雅草卓伊凡
星云智控自定义物联网实时监控模板-为何成为痛点?物联网设备的多样化-优雅草卓伊凡
162 8
Java 大视界 -- 基于 Java 的大数据实时流处理在工业物联网设备状态监测中的应用与挑战(167)
本文围绕基于 Java 的大数据实时流处理技术,深入探讨其在工业物联网设备状态监测中的应用与挑战。不仅介绍了技术架构、原理和案例,还引入边缘计算技术,提出应对数据质量、性能和安全等问题的策略。
|
8月前
|
存储 监控 安全
工业物联网关应用:PLC数据通过智能网关上传阿里云实战
本文介绍如何使用智能网关将工厂PLC数据传输至阿里云平台,适合中小企业远程监控设备状态。硬件准备包括三菱FX3U PLC、4G智能网关和24V电源。接线步骤涵盖PLC编程口与网关连接、运行状态检测及天线电源接入。配置过程涉及通讯参数、阿里云对接和数据点映射。PLC程序关键点包括数据上传触发和温度值处理。阿里云平台操作包含实时数据查看、数据可视化和规则引擎设置。最后提供常见故障排查表和安全建议,确保系统稳定运行。
717 1
|
12月前
|
存储 安全 物联网
政府在推动物联网技术标准和规范的统一方面可以发挥哪些作用?
政府在推动物联网技术标准和规范的统一方面可以发挥哪些作用?
384 60
|
12月前
|
安全 物联网 物联网安全
制定统一的物联网技术标准和规范的难点有哪些?
制定统一的物联网技术标准和规范的难点有哪些?
430 58
|
12月前
|
存储 数据采集 物联网
物联网技术在物流领域的应用会遇到哪些挑战?
物联网技术在物流领域的应用会遇到哪些挑战?
631 60

相关产品

  • 物联网平台