ThingsBoard MQTT 设备链接

# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/device/device-mqtt-java/

一、概述

1.Eclipse Paho

1.1.Eclipse Paho Java Client
https://eclipse.dev/paho/index.php?page=downloads.php
https://eclipse.dev/paho/index.php?page=clients/java/index.php

https://github.com/eclipse/paho.mqtt.java

在这里插入图片描述
在这里插入图片描述

1.2.Getting Started

Dependency definition for MQTTv3 client

<project ...>
<repositories>
    <repository>
        <id>Eclipse Paho Repo</id>
        <url>%REPOURL%</url>
    </repository>
</repositories>
...
<dependencies>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>%VERSION%</version>
    </dependency>
</dependencies>
</project>

Dependency definition for MQTTv5 client

<project ...>
<repositories>
    <repository>
        <id>Eclipse Paho Repo</id>
        <url>%REPOURL%</url>
    </repository>
</repositories>
...
<dependencies>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
        <version>%VERSION%</version>
    </dependency>
</dependencies>
</project>

The included code below is a very basic sample that connects to a server and publishes a message using the MQTTv3 synchronous API. More extensive samples demonstrating the use of the MQTTv3 and MQTTv5 Asynchronous API can be found in the org.eclipse.paho.sample directory of the source.

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;

public class MqttPublishSample {

    public static void main(String[] args) {

        String topic        = "MQTT Examples";
        String content      = "Message from MqttPublishSample";
        int qos             = 2;
        String broker       = "tcp://iot.eclipse.org:1883";
        String clientId     = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: "+broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: "+content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch(MqttException me) {
            System.out.println("reason "+me.getReasonCode());
            System.out.println("msg "+me.getMessage());
            System.out.println("loc "+me.getLocalizedMessage());
            System.out.println("cause "+me.getCause());
            System.out.println("excep "+me);
            me.printStackTrace();
        }
    }
}
1.3.黑马封装
Java自学教程Java物联网开发“尚方宝剑”之EMQ_黑马程序员
https://www.bilibili.com/video/BV1o5411E7V1?p=34&vd_source=1a41e015388b00909f69083f9831969b

二、MQTT客户端

1.客户端程序

1.pom.xml

        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.5</version>
        </dependency>

2.application.yml

server:
  port: 8999
spring:
  application:
    name: mqtt-client

mqtt:
  # MQTT地址
  broker-url: tcp://192.168.202.188:1883
  # 客户端ID,随机定义
  client-id: emq-client-1111
  # 设备访问令牌
  username: 12Wt6lPaEplx5qKWg9qZ
  # 密码
  password:

3.工具类程序源码

EmqClient

package com.iiotos.mqtt;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Created by 传智播客*黑马程序员.
 */
@Component
public class EmqClient {
    
    private static final Logger log = LoggerFactory.getLogger(EmqClient.class);
    
    private IMqttClient mqttClient;
    
    @Autowired
    private MqttProperties mqttProperties;
    
    @Autowired
    private MqttCallback mqttCallback;
    
    @PostConstruct
    public void init(){
        MqttClientPersistence mempersitence = new MemoryPersistence();
        try {
            mqttClient = new MqttClient(mqttProperties.getBrokerUrl(),mqttProperties.getClientId(),mempersitence);
        } catch (MqttException e) {
            log.error("初始化客户端mqttClient对象失败,errormsg={},brokerUrl={},clientId={}",e.getMessage(),mqttProperties.getBrokerUrl(),mqttProperties.getClientId());
        }

    }

    /**
     * 连接broker
     * @param username
     * @param password
     */
    public void connect(String username,String password){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setCleanSession(true);
        
        mqttClient.setCallback(mqttCallback);

        try {
            mqttClient.connect(options);
        } catch (MqttException e) {
            log.error("mqtt客户端连接服务端失败,失败原因{}",e.getMessage());
        }
    }

    /**
     * 断开连接
     */
    @PreDestroy
    public void disConnect(){
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            log.error("断开连接产生异常,异常信息{}",e.getMessage());
        }
    }

    /**
     * 重连
     */
    public void reConnect(){
        try {
            mqttClient.reconnect();
        } catch (MqttException e) {
            log.error("重连失败,失败原因{}",e.getMessage());
        }
    }

    /**
     * 发布消息
     * @param topic
     * @param msg
     * @param qos
     * @param retain
     */
    public void publish(String topic, String msg, QosEnum qos, boolean retain){

        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(msg.getBytes());
        mqttMessage.setQos(qos.value());
        mqttMessage.setRetained(retain);
        try {
            mqttClient.publish(topic,mqttMessage);
        } catch (MqttException e) {
            log.error("发布消息失败,errormsg={},topic={},msg={},qos={},retain={}",e.getMessage(),topic,msg,qos.value(),retain);
        }

    }

    /**
     * 订阅
     * @param topicFilter
     * @param qos
     */
    public void subscribe(String topicFilter,QosEnum qos){
        try {
            mqttClient.subscribe(topicFilter,qos.value());
        } catch (MqttException e) {
            log.error("订阅主题失败,errormsg={},topicFilter={},qos={}",e.getMessage(),topicFilter,qos.value());
        }

    }

    /**
     * 取消订阅
     * @param topicFilter
     */
    public void unSubscribe(String topicFilter){
        try {
            mqttClient.unsubscribe(topicFilter);
        } catch (MqttException e) {
            log.error("取消订阅失败,errormsg={},topicfiler={}",e.getMessage(),topicFilter);
        }
    }
    
}

MessageCallback

package com.iiotos.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created by 传智播客*黑马程序员.
 */
@Component
public class MessageCallback implements MqttCallback {
    
    private static final Logger log = LoggerFactory.getLogger(MessageCallback.class);

    /**
     * 丢失了对服务端的连接后触发的回调
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        // 资源的清理  重连
        log.info("丢失了对服务端的连接");
    }

    /**
     * 应用收到消息后触发的回调
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("订阅者订阅到了消息,topic={},messageid={},qos={},payload={}",
                topic,
                message.getId(),
                message.getQos(),
                new String(message.getPayload()));
    }

    /**
     * 消息发布者消息发布完成产生的回调
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        int messageId = token.getMessageId();
        String[] topics = token.getTopics();
        log.info("消息发布完成,messageid={},topics={}",messageId,topics);
    }
}

MqttProperties

package com.iiotos.mqtt;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * Created by 传智播客*黑马程序员.
 */
@Configuration
@ConfigurationProperties(prefix = "mqtt")
public class MqttProperties {
    
    private String brokerUrl;
    
    private String clientId;
    
    private String username;
    
    private String password;

    public String getBrokerUrl() {
        return brokerUrl;
    }

    public void setBrokerUrl(String brokerUrl) {
        this.brokerUrl = brokerUrl;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "MqttProperties{" +
                "brokerUrl='" + brokerUrl + '\'' +
                ", clientId='" + clientId + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

QosEnum

package com.iiotos.mqtt;

/**
 * Created by 传智播客*黑马程序员.
 */
public enum QosEnum {
    QoS0(0),QoS1(1),QoS2(2);


    private final int value;

    QosEnum(int value) {
        this.value = value;
    }
    
    public int value(){
        return this.value;
    }
}

4.测试代码

@EnableScheduling
@SpringBootApplication
public class MqttClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(MqttClientApplication.class, args);
    }

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init(){
        //连接服务端
        emqClient.connect(properties.getUsername(),properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("testtopic/#", QosEnum.QoS2);
        //开启一个新的线程 每隔5秒去向 testtopic/123
        new Thread(()->{
            while (true){
                String content = "{\n" +
                        "\t\"mqtt-1\": 1003,\n" +
                        "\t\"mqtt-2\": \"java data3\"\n" +
                        "}";

                emqClient.publish("v1/devices/me/telemetry",content,
                        QosEnum.QoS1,false);
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
}

2.客户端测试

参考工程:mqtt-client

1.案例

@Component
public class CaseTest {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init(){
        //连接服务端
        emqClient.connect(properties.getUsername(),properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("testtopic/#", QosEnum.QoS2);
    }

    @Scheduled(fixedRate = 2000)
    public void publish(){
//        String content = "{\n" +
//                "\t\"mqtt-100\": 1000,\n" +
//                "\t\"mqtt-200\": \"java data\"\n" +
//                "}";

        String content = "{\n" +
                "\t\"mqtt-10\": 10011,\n" +
                "\t\"mqtt-20\": \"java data11\"\n" +
                "}";

        emqClient.publish("v1/devices/me/telemetry",content,
                QosEnum.QoS1,false);
    }
}

2.案例

import com.iiotos.mqtt.EmqClient;
import com.iiotos.mqtt.MqttProperties;
import com.iiotos.mqtt.QosEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class BasicTest {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init(){
        //连接服务端
        emqClient.connect(properties.getUsername(),properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("testtopic/#", QosEnum.QoS2);
        //开启一个新的线程 每隔5秒去向 testtopic/123
        new Thread(()->{
            while (true){
                String content = "{\n" +
                        "\t\"mqtt-10\": 10011,\n" +
                        "\t\"mqtt-20\": \"java data11\"\n" +
                        "}";

                emqClient.publish("v1/devices/me/telemetry",content,
                        QosEnum.QoS1,false);
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
}
# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/device/device-mqtt-java/
  • 19
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
接触Thingsboard用得到!!! 目录 1  参考资料 5  文档目的 6 第一章 项目框架整理说明 7 1.1 项目框架说明 7 1.1.1 package包功能描述 8 1.1.2 thingsboard开发主要涉及到的包 10 1.1.3 thingsboard代码类及接口说明 10 第二章 thingsboard涉及到的流程图 12 2.1 物联网网关架构 12 2.2 ThingsBoard微服务架构 13 2.3 Thingsboard产品架构 13 2.4 Thingsboard规则引擎 14 2.5 ThingsBoard Architecture 15 第三章 项目框架涉及到的第三方包或插件 17 3.1 Thingsboard 包 17 第四章 ThingsBoard设备连接协议 23 4.1 订阅消息传递协议(MQTT) 23 4.2 请求响应模式(CoAP) 23 4.3 请求响应模式(HTTP ) 24 第五章 ThingsBoard打包 25 5.1 后端打包 25 5.2 前端打包方UI 25 第六章 ThingsBoard框架日志 26 第七章 ThingsBoard数据库 目录 目录 1  参考资料 5  文档目的 6 第一章 项目框架整理说明 7 第二章 thingsboard涉及到的流程图 12 第三章 项目框架涉及到的第三方包或插件 17 第四章 ThingsBoard设备连接协议 23 第五章 ThingsBoard打包 25 第六章 ThingsBoard框架日志 26 第七章 ThingsBoard数据库 27 第八章 官网主要文档目录 28 第九章 前端技术概述 29 第十章 关于Thingsboard开发环境部署 30 第十一章 数据库表结构 32 错误!未定义书签。 7.1 关系数据库(使用了2个数据库) 27 7.2 非关系数据库(redis) 27 第八章 官网主要文档目录 28 第九章 前端技术概述 29 9.1 前端包括哪些技术点 29 9.2 前端技术描述 29 第十章 关于Thingsboard开发环境部署 30 第十一章 数据库表结构 32
Thingsboard是一个开源的物联网平台,它可以用于集成和管理物联网设备。要连接ThingsboardMQTT网关,需要遵循以下步骤: 1. 创建设备:首先,在Thingsboard平台上创建一个设备。你可以在设备管理页面创建设备,并分配一个设备标识符(Device ID)和设备令牌(Device Token)。 2. 配置MQTT网关:然后,配置你的MQTT网关以便与Thingsboard平台连接。在网关的配置文件中,你需要指定Thingsboard平台的连接细节,例如服务器地址、端口、设备标识符等。 3. 连接MQTT网关:网关启动后,它将自动连接Thingsboard平台。它将使用预先配置的设备标识符和设备令牌进行身份验证。 4. 设备上报数据:在设备上报数据时,可以通过网关将数据发送到Thingsboard平台。MQTT网关会将数据发布到指定的MQTT主题上,该主题的名称是由设备标识符和“telemetry”(遥测数据)组成的。 5. 数据可视化和管理:Thingsboard平台将接收来自MQTT网关的数据,并将其存储在数据库中。你可以使用Thingsboard提供的仪表板功能来可视化和监控设备数据。还可以在平台上进行设备管理、数据分析和规则引擎配置等操作。 需要注意的是,连接MQTT网关和Thingsboard平台的具体步骤可能会因所使用的网关和Thingsboard的版本而有所不同。因此,在实际操作时,建议参考相关文档和官方指南以获得准确的步骤和配置细节。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IoTHub - 物联网开源技术社区

支持开源技术! 传播开源文化!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值