ThingsBoard 二次开发 - 设备控制

# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/dev/dev-rpc/

一、RPC规划

1.服务端RPC

  1. 服务端RPC分:单向RPC、双向RPC
  2. 应用端通过REST API发送RPC请求
  3. 双向RPC通response返回命令结果

服务端RPC调用可以分为单向和双向:

  • 单向RPC请求直接发送请求,并且不对设备响应做任何处理
    在这里插入图片描述

  • 双向RPC请求会发送到设备,并且超时期间内接收到来自设备的响应
    在这里插入图片描述

2.客户端RPC

  1. 客户端RPC从设备端发送到平台
  2. ThingsBoard没有提供REST API
  3. ThingsBoard通过规则引擎整合元数据
  4. ThingsBoard通过规则引擎把消息路由到消息队列(RabbitMQ或Kafka、EMQX),根据设备类型建topic
  5. 消息队列(RabbitMQ)根据topic消费数据,处理命令

在这里插入图片描述

二、准备工作

1.创建设备

在这里插入图片描述

2.创建规则引擎

2.1.创建RPC规则链

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

3.RPC数据

3.1.双向PRC数据
{
    "method": "getValue",
    "params": "{\"pin\":88,\"value\":99}",
    "additionalInfo": null
}
{
    "deviceName": "Test-rpc",
    "deviceType": "default",
    "expirationTime": "1696921879114",
    "oneway": "false",
    "originServiceId": "VM-24-10-centos",
    "persistent": "false",
    "requestUUID": "2e023965-6e0b-4b28-8523-26380de2aa98"
}
3.2.单向RPC数据
{
    "method": "setValue",
    "params": "{\"pin\":7,\"value\":1}",
    "additionalInfo": null
}
{
    "deviceName": "Test-rpc",
    "deviceType": "default",
    "expirationTime": "1696921942198",
    "oneway": "true",
    "originServiceId": "VM-24-10-centos",
    "persistent": "false",
    "requestUUID": "a238826d-0f8d-49dc-8240-d3382c14f9a2"
}
3.3.客户端RPC数据
{
    "method": "getServerValue",
    "params": ""
}
{
    "deviceName": "Test-rpc",
    "deviceType": "default",
    "requestId": "1",
    "serviceId": "VM-24-10-centos",
    "sessionId": "e8c36497-9601-4df5-b8d6-3755bf6c500c"
}

三、REST API

1.RPC API

在这里插入图片描述

2.单向RPC

在这里插入图片描述

# POST路径
/api/rpc/oneway/{deviceId}

# 设备ID  Test-rpc
eb9cc990-6711-11ee-afb9-c790163a721a

# 发送数据
{
  "method": "setValue",
  "params": {
    "pin": 7,
    "value": 1
  },
  "persistent": false,
  "timeout": 5000
}

http://localhost:8999/rpc/oneway
package com.iothub.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class OneRPC {

    public void sendRpc() throws JsonProcessingException {
        String baseURL = "http://82.157.166.86:8080";
        String token = Login.getToken();
        // 地址:/api/rpc/oneway/{deviceId}
        // 设备ID:  eb9cc990-6711-11ee-afb9-c790163a721a
        String apiUrl = "/api/rpc/oneway/{deviceId}";
        String deviceId = "eb9cc990-6711-11ee-afb9-c790163a721a";
        HttpHeaders headers = new HttpHeaders();
        //headers.add("Authorization", "Bearer "+ mainToken);
        headers.set("X-Authorization", "Bearer " + token);
        //headers.set("Content-Type", "application/json");
        headers.setContentType(MediaType.APPLICATION_JSON);

        String body = "{\n" +
                "  \"method\": \"setValue\",\n" +
                "  \"params\": {\n" +
                "    \"pin\": 7,\n" +
                "    \"value\": 1\n" +
                "  },\n" +
                "  \"persistent\": false,\n" +
                "  \"timeout\": 5000\n" +
                "}";

        HttpEntity entity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity response = restTemplate.exchange(baseURL + apiUrl, HttpMethod.POST, entity, String.class, new Object[]{deviceId});
        System.out.println(response);
        if (response.getStatusCodeValue() == 200) {
            String device = (String) response.getBody();
            System.out.println(response.getBody());
        }
    }
}

3.双向RPC

在这里插入图片描述

# POST路径
/api/rpc/twoway/{deviceId}

# 设备ID  Test-rpc
eb9cc990-6711-11ee-afb9-c790163a721a

# 发送数据
{
  "method": "getValue",
  "params": {
    "pin": 88,
    "value": 99
  },
  "persistent": false,
  "timeout": 5000
}

http://localhost:8999/rpc/twoway
# 响应
v1/devices/me/rpc/request/$request_id
v1/devices/me/rpc/response/$request_id

{
   "pin": 4,
   "value": 1,
   "changed": true
}

订阅者订阅到了消息,topic=v1/devices/me/rpc/request/10,messageid=1,qos=1,payload={"method":"getValue","params":{"pin":88,"value":99}}
package com.iothub.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class TwoRPC {

    public void sendRpc() throws JsonProcessingException {

        String baseURL = "http://82.157.166.86:8080";
        String token = Login.getToken();

        // 地址:/api/rpc/oneway/{deviceId}
        // 设备ID:  eb9cc990-6711-11ee-afb9-c790163a721a
        String apiUrl = "/api/rpc/twoway/{deviceId}";
        String deviceId = "eb9cc990-6711-11ee-afb9-c790163a721a";
        HttpHeaders headers = new HttpHeaders();
        //headers.add("Authorization", "Bearer "+ mainToken);
        headers.set("X-Authorization", "Bearer " + token);
        //headers.set("Content-Type", "application/json");
        headers.setContentType(MediaType.APPLICATION_JSON);

        String body = "{\n" +
                "  \"method\": \"getValue\",\n" +
                "  \"params\": {\n" +
                "    \"pin\": 88,\n" +
                "    \"value\": 99\n" +
                "  },\n" +
                "  \"persistent\": false,\n" +
                "  \"timeout\": 5000\n" +
                "}";

        HttpEntity entity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity response = restTemplate.exchange(baseURL + apiUrl, HttpMethod.POST, entity, String.class, new Object[]{deviceId});
        System.out.println(response);
        if (response.getStatusCodeValue() == 200) {
            String device = (String) response.getBody();
            System.out.println(response.getBody());
        }
    }
}

四、服务端RPC

1.双向PRC

1.1.REST API
package com.iothub.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class TwoRPC {

    public void sendRpc() throws JsonProcessingException {

        String baseURL = "http://82.157.166.86:8080";
        String token = Login.getToken();

        // 地址:/api/rpc/oneway/{deviceId}
        // 设备ID:  eb9cc990-6711-11ee-afb9-c790163a721a
        String apiUrl = "/api/rpc/twoway/{deviceId}";
        String deviceId = "eb9cc990-6711-11ee-afb9-c790163a721a";
        HttpHeaders headers = new HttpHeaders();
        //headers.add("Authorization", "Bearer "+ mainToken);
        headers.set("X-Authorization", "Bearer " + token);
        //headers.set("Content-Type", "application/json");
        headers.setContentType(MediaType.APPLICATION_JSON);

        String body = "{\n" +
                "  \"method\": \"getValue\",\n" +
                "  \"params\": {\n" +
                "    \"pin\": 88,\n" +
                "    \"value\": 99\n" +
                "  },\n" +
                "  \"persistent\": false,\n" +
                "  \"timeout\": 5000\n" +
                "}";

        HttpEntity entity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity response = restTemplate.exchange(baseURL + apiUrl, HttpMethod.POST, entity, String.class, new Object[]{deviceId});
        System.out.println(response);
        if (response.getStatusCodeValue() == 200) {
            String device = (String) response.getBody();
            System.out.println(response.getBody());
        }
    }
}
1.2.设备(MQTT)
package com.iothub.rpc;
import com.iothub.mqtt.EmqClient;
import com.iothub.mqtt.MqttProperties;
import com.iothub.mqtt.QosEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class ServerRpc {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init(){
        //连接服务端
        emqClient.connect(properties.getUsername(),properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("v1/devices/me/rpc/request/+", QosEnum.QoS1);
    }
}
# MessageCallback
 
     /**
     * 应用收到消息后触发的回调
     * @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()));

/
        // 双向RPC
        // v1/devices/me/rpc/request/$request_id
        String[] buff = topic.split("/");
        String request_id = buff[buff.length-1];
        // 客户端PUBLISH下面主题进行响应:
        // v1/devices/me/rpc/response/$request_id
        String retData = "{\n" +
                "   \"pin\": 4,\n" +
                "   \"value\": 1,\n" +
                "   \"changed\": true\n" +
                "}";

        emqClient.publish("v1/devices/me/rpc/response/" + request_id, retData, QosEnum.QoS1,false);
    }
1.3.测试
# POST路径
/api/rpc/twoway/{deviceId}

# 设备ID  Test-rpc
eb9cc990-6711-11ee-afb9-c790163a721a

# 发送数据
{
  "method": "getValue",
  "params": {
    "pin": 88,
    "value": 99
  },
  "persistent": false,
  "timeout": 5000
}

# 返回结果
{
	"pin": 4,
	"value": 1,
	"changed": true
}

http://localhost:8999/rpc/twoway
2023-10-10 15:28:30.926  INFO 23200 --- [ emq-client-rpc] com.iothub.mqtt.MessageCallback          : 订阅者订阅到了消息,topic=v1/devices/me/rpc/request/32,messageid=5,qos=1,payload={"method":"getValue","params":{"pin":88,"value":99}}
2023-10-10 15:28:30.933  INFO 23200 --- [ emq-client-rpc] com.iothub.mqtt.MessageCallback          : 消息发布完成,messageid=6,topics=[v1/devices/me/rpc/response/32]
<200,{"pin":4,"value":1,"changed":true},[Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", Content-Type:"application/json", Transfer-Encoding:"chunked", Date:"Tue, 10 Oct 2023 07:28:30 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>
{"pin":4,"value":1,"changed":true}

2.单向RPC

2.1.RESTAPI
package com.iothub.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class OneRPC {

    public void sendRpc() throws JsonProcessingException {

        String baseURL = "http://82.157.166.86:8080";
        String token = Login.getToken();

        // 地址:/api/rpc/oneway/{deviceId}
        // 设备ID:  eb9cc990-6711-11ee-afb9-c790163a721a
        String apiUrl = "/api/rpc/oneway/{deviceId}";
        String deviceId = "eb9cc990-6711-11ee-afb9-c790163a721a";
        HttpHeaders headers = new HttpHeaders();
        //headers.add("Authorization", "Bearer "+ mainToken);
        headers.set("X-Authorization", "Bearer " + token);
        //headers.set("Content-Type", "application/json");
        headers.setContentType(MediaType.APPLICATION_JSON);

        String body = "{\n" +
                "  \"method\": \"setValue\",\n" +
                "  \"params\": {\n" +
                "    \"pin\": 7,\n" +
                "    \"value\": 1\n" +
                "  },\n" +
                "  \"persistent\": false,\n" +
                "  \"timeout\": 5000\n" +
                "}";

        HttpEntity entity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity response = restTemplate.exchange(baseURL + apiUrl, HttpMethod.POST, entity, String.class, new Object[]{deviceId});
        System.out.println(response);
        if (response.getStatusCodeValue() == 200) {
            String device = (String) response.getBody();
            System.out.println(response.getBody());
        }
    }
}
package com.iothub.rest;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

public class Login {

    public static String getToken(){

        String username = "tenant@thingsboard.org";
        String password = "tenant";
        String baseURL = "http://82.157.166.86:8080";
        RestTemplate restTemplate = new RestTemplate();

        // 登录
        long ts = System.currentTimeMillis();
        Map<String, String> loginRequest = new HashMap();
        loginRequest.put("username", username);
        loginRequest.put("password", password);
        ResponseEntity<JsonNode> tokenInfo1 = restTemplate.postForEntity(baseURL + "/api/auth/login", loginRequest, JsonNode.class, new Object[0]);
        JsonNode tokenInfo = (JsonNode)tokenInfo1.getBody();
        //System.out.println(tokenInfo);

        // 解析数据
        String mainToken = tokenInfo.get("token").asText();
        String refreshToken = tokenInfo.get("refreshToken").asText();
        //System.out.println("token: " + tokenInfo);
        //System.out.println("refreshToken: " + refreshToken);

        return mainToken;
    }
}
2.2.设备(MQTT)

同 1.2.设备(MQTT)

2.3.测试
# POST路径
/api/rpc/oneway/{deviceId}

# 设备ID  Test-rpc
eb9cc990-6711-11ee-afb9-c790163a721a

# 发送数据
{
  "method": "setValue",
  "params": {
    "pin": 7,
    "value": 1
  },
  "persistent": false,
  "timeout": 5000
}

http://localhost:8999/rpc/oneway
<200,[Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", Content-Length:"0", Date:"Tue, 10 Oct 2023 07:33:01 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>
null
2023-10-10 15:33:01.593  INFO 23200 --- [ emq-client-rpc] com.iothub.mqtt.MessageCallback          : 订阅者订阅到了消息,topic=v1/devices/me/rpc/request/33,messageid=6,qos=1,payload={"method":"setValue","params":{"pin":7,"value":1}}
2023-10-10 15:33:01.600  INFO 23200 --- [ emq-client-rpc] com.iothub.mqtt.MessageCallback          : 消息发布完成,messageid=7,topics=[v1/devices/me/rpc/response/33]

五、客户端RPC

1.规则引擎

1.1.整合元数据

在这里插入图片描述

{
    "deviceName": "Test-rpc",
    "deviceType": "default",
    "requestId": "1",
    "serviceId": "VM-24-10-centos",
    "sessionId": "e8c36497-9601-4df5-b8d6-3755bf6c500c"
}
1.2.按设备类型流转命令

在这里插入图片描述

# 按设备类型流转命令

if(msg.deviceType === 'test-telemetry') {
    return ['test-telemetry'];
} else {
    return ['default'];
}
1.3.RabbitMQ

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

1.4.完整规则链

在这里插入图片描述

2.RabbitMQ

队列:telemetry-queue、telemetry-default-queue

交换机:telemetry-devicetype-exchange

在这里插入图片描述

3.设备(MQTT)

package com.iothub.rpc;
import com.iothub.mqtt.EmqClient;
import com.iothub.mqtt.MqttProperties;
import com.iothub.mqtt.QosEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class ClientRpc {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init(){
        //连接服务端
        emqClient.connect(properties.getUsername(),properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("v1/devices/me/rpc/response/+", QosEnum.QoS1);
    }

    @Scheduled(fixedRate = 3000)
    public void publish(){
        String data = getData();
        emqClient.publish("v1/devices/me/rpc/request/1",data,QosEnum.QoS1,false);
    }

    private String getData(){

        String data = "{\n" +
                "\t\"method\": \"getServerValue\",\n" +
                "\t\"params\": \"\"\n" +
                "}";

        return data;
    }
}

4.测试

{
	"method": "getServerValue",
	"params": "",
	"deviceType": "default",
	"deviceName": "Test-rpc"
}

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

# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/dev/dev-rpc/
  • 19
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Thingsboard是一个开源的IoT平台,提供了许多基础功能,包括设备管理、数据可视化、规则引擎等。如果需要根据自己的业务需求进行二次开发,可以通过自定义插件、调用API或者直接修改源代码来实现。下面是基于Thingsboard源代码的CURD后端开发流程: 1. 安装并启动Thingsboard 首先需要安装并启动Thingsboard,可以参考官方文档进行操作。 2. 创建新的数据模型 在Thingsboard中,数据模型是指设备、传感器、属性等实体间的关系。如果需要添加新的实体,可以通过创建新的数据模型来实现。具体操作可以参考官方文档。 3. 创建新的REST API 在Thingsboard中,可以通过创建新的REST API来实现CURD操作。具体操作如下: (1)在源代码中创建新的Java类,继承AbstractWebsocketHandler类。 (2)在新的Java类中实现对应的HTTP请求处理方法,比如GET、POST、DELETE等。 (3)在新的Java类中实现对应的数据模型CURD操作,比如查询、新增、修改、删除等。 (4)在新的Java类中定义对应的路由信息,比如URL路径、请求方法等。 (5)在Thingsboard配置文件中定义新的REST API路由信息。 4. 测试新的REST API 完成以上步骤后,可以启动Thingsboard并测试新的REST API是否能够正常工作。可以使用Postman等工具进行测试,也可以在自己的应用中调用该API。 总的来说,通过自定义REST API可以实现对Thingsboard二次开发,满足不同业务需求。当然,需要注意的是,修改源代码可能会影响到系统的稳定性和可维护性,需要谨慎操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IoTHub - 物联网开源技术社区

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

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

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

打赏作者

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

抵扣说明:

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

余额充值