#init
This commit is contained in:
90
maibu-iotDA/pom.xml
Normal file
90
maibu-iotDA/pom.xml
Normal file
@@ -0,0 +1,90 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.maibu</groupId>
|
||||
<artifactId>MiddlePlatform</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>maibu-iotDA</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.maibu</groupId>
|
||||
<artifactId>maibu-common</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.qpid</groupId>
|
||||
<artifactId>qpid-jms-client</artifactId>
|
||||
<version>0.50.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.20.0</version> <!-- 使用最新版 -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.20.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.8</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-core</artifactId>
|
||||
<version>4.5.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.huaweicloud</groupId>
|
||||
<artifactId>iot-device-sdk-java</artifactId>
|
||||
<version>1.2.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.huaweicloud.sdk</groupId>
|
||||
<artifactId>huaweicloud-sdk-core</artifactId>
|
||||
<version>3.1.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.huaweicloud.sdk</groupId>
|
||||
<artifactId>huaweicloud-sdk-iotda</artifactId>
|
||||
<version>3.1.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.maibu</groupId>
|
||||
<artifactId>maibu-framework</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.maibu</groupId>
|
||||
<artifactId>maibu-netty-server</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.maibu.controller;
|
||||
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.common.utils.json.JsonUtils;
|
||||
import com.fastbee.dto.IoTDACommandDTO;
|
||||
import com.fastbee.dto.IoTDARuleDTO;
|
||||
import com.fastbee.service.IoTDADeviceService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/iotDA/device")
|
||||
public class IoTDADeviceController {
|
||||
|
||||
@Autowired
|
||||
private IoTDADeviceService ioTDADeviceService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public AjaxResult list() {
|
||||
return AjaxResult.success(ioTDADeviceService.list());
|
||||
}
|
||||
|
||||
@GetMapping("/detail")
|
||||
public AjaxResult detail(@RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.detail(deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/command")
|
||||
public AjaxResult command(@RequestBody IoTDACommandDTO dto) {
|
||||
return AjaxResult.success(ioTDADeviceService.command(dto));
|
||||
}
|
||||
|
||||
@GetMapping("/ruleList")
|
||||
public AjaxResult ruleList() {
|
||||
return AjaxResult.success(ioTDADeviceService.ruleList());
|
||||
}
|
||||
|
||||
@PostMapping("/deleteRule")
|
||||
public AjaxResult deleteRule(@RequestParam String ruleId) {
|
||||
return AjaxResult.success(ioTDADeviceService.deleteRule(ruleId));
|
||||
}
|
||||
|
||||
@PostMapping("/createRule")
|
||||
public AjaxResult createRule(@RequestBody IoTDARuleDTO dto) {
|
||||
return AjaxResult.success(ioTDADeviceService.createRule(dto));
|
||||
}
|
||||
|
||||
@GetMapping("/ruleActionList")
|
||||
public AjaxResult ruleActionList(@RequestParam String ruleId) {
|
||||
return AjaxResult.success(ioTDADeviceService.ruleActionList(ruleId));
|
||||
}
|
||||
|
||||
@PostMapping("/createRuleAction")
|
||||
public AjaxResult createRuleAction(@RequestParam String ruleId) {
|
||||
return AjaxResult.success(ioTDADeviceService.createRuleAction(ruleId));
|
||||
}
|
||||
|
||||
@PostMapping("/deleteRuleAction")
|
||||
public AjaxResult deleteRuleAction(@RequestParam String actionId) {
|
||||
return AjaxResult.success(ioTDADeviceService.deleteRuleAction(actionId));
|
||||
}
|
||||
|
||||
@PostMapping("/callback")
|
||||
public AjaxResult callback(@RequestBody Object obj) {
|
||||
System.out.println("收到触发消息:" + JsonUtils.toJsonString(obj));
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
|
||||
@PostMapping("/addDevice")
|
||||
public AjaxResult addDevice(@RequestParam String nodeId) throws IOException {
|
||||
return AjaxResult.success(ioTDADeviceService.addDevice(nodeId));
|
||||
}
|
||||
|
||||
@PostMapping("/deleteDevice")
|
||||
public AjaxResult deleteDevice(@RequestParam String deviceId) {
|
||||
ioTDADeviceService.deleteDevice(deviceId);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/updateDevice")
|
||||
public AjaxResult updateDevice(@RequestParam String deviceName, @RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.updateDevice(deviceName, deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/freezeDevice")
|
||||
public AjaxResult freezeDevice(@RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.freezeDevice(deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/unfreezeDevice")
|
||||
public AjaxResult unfreezeDevice(@RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.unfreezeDevice(deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/createMessage")
|
||||
public AjaxResult createMessage(@RequestParam String deviceId, @RequestParam String json) {
|
||||
return AjaxResult.success(ioTDADeviceService.createMessage(deviceId, json));
|
||||
}
|
||||
|
||||
@PostMapping("/listDeviceMessages")
|
||||
public AjaxResult listDeviceMessages(@RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.listDeviceMessages(deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/addDeviceGroup")
|
||||
public AjaxResult addDeviceGroup(@RequestParam String name) {
|
||||
return AjaxResult.success(ioTDADeviceService.addDeviceGroup(name));
|
||||
}
|
||||
|
||||
// actionId: addDevice/removeDevice
|
||||
@PostMapping("/manageDeviceGroup")
|
||||
public AjaxResult manageDeviceGroup(@RequestParam String groupId, @RequestParam String actionId, @RequestParam String deviceId) {
|
||||
return AjaxResult.success(ioTDADeviceService.manageDeviceGroup(groupId, actionId, deviceId));
|
||||
}
|
||||
|
||||
@PostMapping("/deleteDeviceGroup")
|
||||
public AjaxResult deleteDeviceGroup(@RequestParam String groupId) {
|
||||
return AjaxResult.success(ioTDADeviceService.deleteDeviceGroup(groupId));
|
||||
}
|
||||
|
||||
@PostMapping("/listDeviceGroups")
|
||||
public AjaxResult listDeviceGroups() {
|
||||
return AjaxResult.success(ioTDADeviceService.listDeviceGroups());
|
||||
}
|
||||
|
||||
@PostMapping("/showDevicesInGroup")
|
||||
public AjaxResult showDevicesInGroup(@RequestParam String groupId) {
|
||||
return AjaxResult.success(ioTDADeviceService.showDevicesInGroup(groupId));
|
||||
}
|
||||
|
||||
@PostMapping("/updateDeviceGroup")
|
||||
public AjaxResult updateDeviceGroup(@RequestParam String groupId, @RequestParam String name, @RequestParam String description) {
|
||||
return AjaxResult.success(ioTDADeviceService.updateDeviceGroup(groupId, name, description));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
10
maibu-iotDA/src/main/java/com/maibu/dto/IoTDACommandDTO.java
Normal file
10
maibu-iotDA/src/main/java/com/maibu/dto/IoTDACommandDTO.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.maibu.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class IoTDACommandDTO {
|
||||
private String commandName;
|
||||
private Object param;
|
||||
private String deviceId;
|
||||
}
|
||||
10
maibu-iotDA/src/main/java/com/maibu/dto/IoTDARuleDTO.java
Normal file
10
maibu-iotDA/src/main/java/com/maibu/dto/IoTDARuleDTO.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.maibu.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class IoTDARuleDTO {
|
||||
private String resource; // device.property
|
||||
private String event;
|
||||
private String ruleName;//report
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.maibu.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class IoTDADeviceRunningStatus {
|
||||
|
||||
private String deviceId;
|
||||
|
||||
private String voltage; //电压
|
||||
|
||||
private String latitude;//纬度
|
||||
|
||||
private String longitude;//经度
|
||||
|
||||
private Integer onlineStatus;
|
||||
|
||||
private String time;
|
||||
|
||||
private String battery;//电池电量
|
||||
|
||||
private String workingArea;//作业面积
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.maibu.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
@Data
|
||||
@TableName("iotda_device_secret")
|
||||
public class IoTDADeviceSecret implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String deviceId;
|
||||
|
||||
private String secretId;
|
||||
|
||||
}
|
||||
144
maibu-iotDA/src/main/java/com/maibu/init/InitIotResource.java
Normal file
144
maibu-iotDA/src/main/java/com/maibu/init/InitIotResource.java
Normal file
@@ -0,0 +1,144 @@
|
||||
package com.maibu.init;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fastbee.entity.IoTDADeviceSecret;
|
||||
import com.fastbee.mapper.IoTDADeviceSecretMapper;
|
||||
import com.fastbee.memory.IotGlobalMemory;
|
||||
import com.fastbee.utils.IoTDAAMQClient;
|
||||
import com.fastbee.utils.IoTDAMqttClient;
|
||||
import com.huaweicloud.sdk.iotda.v5.model.QueryDeviceSimplify;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.VertxOptions;
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统初始化资源类
|
||||
* 实现CommandLineRunner接口,在Spring Boot启动时自动执行
|
||||
*/
|
||||
@Getter
|
||||
@Component
|
||||
public class InitIotResource implements CommandLineRunner {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(InitIotResource.class);
|
||||
|
||||
@Resource
|
||||
private IoTDAMqttClient ioTDAMqttClient;
|
||||
@Resource
|
||||
private IoTDAAMQClient client;
|
||||
|
||||
@Value("${ioTDA.serverIp}")
|
||||
private String serverIp;
|
||||
|
||||
// @Value("${ioTDA.deviceId}")
|
||||
// private String deviceId;
|
||||
|
||||
@Value("${ioTDA.secret}")
|
||||
private String secret;
|
||||
|
||||
@Value("${ioTDA.serviceId}")
|
||||
private String serviceId;
|
||||
|
||||
@Autowired
|
||||
private IoTDADeviceSecretMapper secretMapper;
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
logger.info("InitResource 开始初始化系统资源...");
|
||||
|
||||
// 初始化Vert.x
|
||||
initResource();
|
||||
logger.info("InitResource 系统资源初始化完成");
|
||||
initDeviceConnectAndMesPush();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化Vert.x
|
||||
*/
|
||||
private void initResource() {
|
||||
try {
|
||||
VertxOptions options = new VertxOptions()
|
||||
.setWorkerPoolSize(20)
|
||||
.setEventLoopPoolSize(10)
|
||||
.setWarningExceptionTime(5000000000L);
|
||||
|
||||
IotGlobalMemory.vertx = Vertx.vertx(options);
|
||||
logger.info("Vert.x 初始化成功");
|
||||
|
||||
IotGlobalMemory.ioTDAAMQClient = this.client;
|
||||
IotGlobalMemory.ioTDAAMQClient.connect();
|
||||
|
||||
List<QueryDeviceSimplify> list = IotGlobalMemory.ioTDAAMQClient.listDevices();
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
list.forEach(x -> {
|
||||
|
||||
LambdaQueryWrapper<IoTDADeviceSecret> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(IoTDADeviceSecret::getDeviceId, x.getDeviceId());
|
||||
IoTDADeviceSecret secret = secretMapper.selectOne(lqw);
|
||||
IoTDAMqttClient c = new IoTDAMqttClient();
|
||||
if (secret == null) {
|
||||
c.secret = this.secret;
|
||||
} else {
|
||||
c.secret = secret.getSecretId();
|
||||
}
|
||||
c.serverIp = this.serverIp;
|
||||
c.serviceId = this.serviceId;
|
||||
c.deviceId = x.getDeviceId();
|
||||
// try {
|
||||
// c.connect(true);
|
||||
// } catch (IOException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
IotGlobalMemory.ioTDAMqttClientMap.put(x.getDeviceId(), c);
|
||||
});
|
||||
}
|
||||
logger.info("iotDevice AMQ 初始化结束");
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("初始化失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void initDeviceConnectAndMesPush() {
|
||||
IotGlobalMemory.vertx.setPeriodic(3000, timerId -> {
|
||||
//todo 查看当前存在的所有设备循环推送状态?
|
||||
try {
|
||||
if (!CollectionUtils.isEmpty(IotGlobalMemory.ioTDAMqttClientMap.values())) {
|
||||
IotGlobalMemory.ioTDAMqttClientMap.values().forEach(x -> {
|
||||
if (x.status != 0) {
|
||||
try {
|
||||
x.judeConnect();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
if (x.status == 0) {
|
||||
x.publishProperty();
|
||||
}
|
||||
});
|
||||
}
|
||||
// if (IotGlobalMemory.ioTDAAMQClient != null) {
|
||||
// IotGlobalMemory.ioTDAAMQClient.deviceShadow(null);
|
||||
// }
|
||||
} catch (Exception e) {
|
||||
logger.error("循环执行设备状态任务异常", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.maibu.mapper;
|
||||
|
||||
import com.fastbee.entity.IoTDADeviceSecret;
|
||||
import com.fastbee.framework.mybatis.mapper.BaseMapperX;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* 设备历史状态
|
||||
*/
|
||||
@Repository
|
||||
public interface IoTDADeviceSecretMapper extends BaseMapperX<IoTDADeviceSecret> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.maibu.memory;
|
||||
|
||||
|
||||
import com.fastbee.utils.IoTDAAMQClient;
|
||||
import com.fastbee.utils.IoTDAMqttClient;
|
||||
import io.vertx.core.Vertx;
|
||||
import lombok.Data;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
@Data
|
||||
public class IotGlobalMemory {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(IotGlobalMemory.class);
|
||||
/**
|
||||
* -- GETTER --
|
||||
* 获取Vert.x实例
|
||||
*/
|
||||
public static Vertx vertx;
|
||||
|
||||
public static Map<String,IoTDAMqttClient> ioTDAMqttClientMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static IoTDAAMQClient ioTDAAMQClient;
|
||||
|
||||
|
||||
/**
|
||||
* 关闭资源
|
||||
*/
|
||||
public void vertxClose() {
|
||||
if (vertx != null) {
|
||||
vertx.close(res -> {
|
||||
if (res.succeeded()) {
|
||||
logger.info("Vert.x 关闭成功");
|
||||
} else {
|
||||
logger.error("Vert.x 关闭失败: {}", res.cause().getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.maibu.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fastbee.dto.IoTDACommandDTO;
|
||||
import com.fastbee.dto.IoTDARuleDTO;
|
||||
import com.fastbee.entity.IoTDADeviceSecret;
|
||||
import com.fastbee.mapper.IoTDADeviceSecretMapper;
|
||||
import com.fastbee.memory.IotGlobalMemory;
|
||||
import com.fastbee.utils.IoTDAMqttClient;
|
||||
import com.huaweicloud.sdk.iotda.v5.model.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class IoTDADeviceService {
|
||||
|
||||
|
||||
@Value("${ioTDA.serverIp}")
|
||||
private String serverIp;
|
||||
|
||||
// @Value("${ioTDA.deviceId}")
|
||||
// private String deviceId;
|
||||
|
||||
@Value("${ioTDA.secret}")
|
||||
private String secret;
|
||||
|
||||
@Value("${ioTDA.serviceId}")
|
||||
private String serviceId;
|
||||
|
||||
@Autowired
|
||||
private IoTDADeviceSecretMapper secretMapper;
|
||||
|
||||
public List<QueryDeviceSimplify> list() {
|
||||
return IotGlobalMemory.ioTDAAMQClient.listDevices();
|
||||
}
|
||||
|
||||
public Object detail(String id) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.deviceShadow(id);
|
||||
}
|
||||
|
||||
public String command(IoTDACommandDTO dto) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.command(dto.getDeviceId(), dto.getCommandName(), dto.getParam());
|
||||
}
|
||||
|
||||
public List<RoutingRule> ruleList() {
|
||||
return IotGlobalMemory.ioTDAAMQClient.ruleList();
|
||||
}
|
||||
|
||||
public String createRule(IoTDARuleDTO dto) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.createRule(dto.getRuleName(), dto.getResource(), dto.getEvent());
|
||||
}
|
||||
|
||||
public String deleteRule(String ruleId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.deleteRule(ruleId);
|
||||
}
|
||||
|
||||
public List<RoutingRuleAction> ruleActionList(String ruleId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.ruleActionList(ruleId);
|
||||
}
|
||||
|
||||
public String createRuleAction(String ruleId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.createRuleAction(ruleId);
|
||||
}
|
||||
|
||||
public String deleteRuleAction(String actionId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.deleteRuleAction(actionId);
|
||||
}
|
||||
|
||||
public String addDevice(String nodeId) throws IOException {
|
||||
AddDeviceResponse response = IotGlobalMemory.ioTDAAMQClient.addDevice(nodeId);
|
||||
String id = null;
|
||||
if (response != null) {
|
||||
id = response.getDeviceId();
|
||||
if (!StringUtils.isEmpty(id)) {
|
||||
LambdaQueryWrapper<IoTDADeviceSecret> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(IoTDADeviceSecret::getDeviceId, id);
|
||||
IoTDADeviceSecret secret = secretMapper.selectOne(lqw);
|
||||
if (secret == null) {
|
||||
secret = new IoTDADeviceSecret();
|
||||
secret.setDeviceId(id);
|
||||
secret.setSecretId(response.getAuthInfo().getSecret());
|
||||
secretMapper.insert(secret);
|
||||
} else {
|
||||
secret.setSecretId(response.getAuthInfo().getSecret());
|
||||
secretMapper.updateById(secret);
|
||||
}
|
||||
IoTDAMqttClient c = new IoTDAMqttClient();
|
||||
c.secret = response.getAuthInfo().getSecret();
|
||||
c.serverIp = this.serverIp;
|
||||
c.serviceId = this.serviceId;
|
||||
c.deviceId = id;
|
||||
// c.connect(true);
|
||||
IotGlobalMemory.ioTDAMqttClientMap.put(id, c);
|
||||
}
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
public void deleteDevice(String id) {
|
||||
IotGlobalMemory.ioTDAAMQClient.deleteDevice(id);
|
||||
IotGlobalMemory.ioTDAMqttClientMap.remove(id);
|
||||
LambdaQueryWrapper<IoTDADeviceSecret> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(IoTDADeviceSecret::getDeviceId, id);
|
||||
secretMapper.delete(lqw);
|
||||
}
|
||||
|
||||
public String updateDevice(String deviceName, String deviceId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.updateDevice(deviceName, deviceId);
|
||||
}
|
||||
|
||||
public String freezeDevice(String deviceId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.freezeDevice(deviceId);
|
||||
}
|
||||
|
||||
public String unfreezeDevice(String deviceId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.unfreezeDevice(deviceId);
|
||||
}
|
||||
|
||||
public String createMessage(String deviceId, String json) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.createMessage(deviceId, json);
|
||||
}
|
||||
|
||||
public List<DeviceMessage> listDeviceMessages(String deviceId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.listDeviceMessages(deviceId);
|
||||
}
|
||||
|
||||
public String addDeviceGroup(String name) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.addDeviceGroup(name);
|
||||
}
|
||||
|
||||
public String manageDeviceGroup(String groupId, String actionId, String deviceId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.manageDeviceGroup(groupId, actionId, deviceId);
|
||||
}
|
||||
|
||||
public String deleteDeviceGroup(String groupId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.deleteDeviceGroup(groupId);
|
||||
}
|
||||
|
||||
public List<DeviceGroupResponseDTO> listDeviceGroups() {
|
||||
return IotGlobalMemory.ioTDAAMQClient.listDeviceGroups();
|
||||
}
|
||||
|
||||
public List<SimplifyDevice> showDevicesInGroup(String groupId) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.showDevicesInGroup(groupId);
|
||||
}
|
||||
|
||||
public String updateDeviceGroup(String groupId, String name, String description) {
|
||||
return IotGlobalMemory.ioTDAAMQClient.updateDeviceGroup(groupId, name, description);
|
||||
}
|
||||
}
|
||||
409
maibu-iotDA/src/main/java/com/maibu/utils/IoTDAAMQClient.java
Normal file
409
maibu-iotDA/src/main/java/com/maibu/utils/IoTDAAMQClient.java
Normal file
@@ -0,0 +1,409 @@
|
||||
package com.maibu.utils;
|
||||
|
||||
import com.fastbee.common.utils.json.JsonUtils;
|
||||
import com.huaweicloud.sdk.core.auth.BasicCredentials;
|
||||
import com.huaweicloud.sdk.core.auth.ICredential;
|
||||
import com.huaweicloud.sdk.core.exception.ConnectionException;
|
||||
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
|
||||
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
|
||||
import com.huaweicloud.sdk.core.region.Region;
|
||||
import com.huaweicloud.sdk.iotda.v5.*;
|
||||
import com.huaweicloud.sdk.iotda.v5.model.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class IoTDAAMQClient {
|
||||
|
||||
@Value("${ioTDA.REGION_ID}")
|
||||
private String REGION_ID;
|
||||
|
||||
@Value("${ioTDA.ENDPOINT}")
|
||||
private String ENDPOINT;
|
||||
|
||||
@Value("${ioTDA.ak}")
|
||||
private String ak;
|
||||
|
||||
@Value("${ioTDA.sk}")
|
||||
private String sk;
|
||||
|
||||
@Value("${ioTDA.projectId}")
|
||||
private String projectId;
|
||||
|
||||
// @Value("${ioTDA.deviceId}")
|
||||
// private String deviceId;
|
||||
|
||||
@Value("${ioTDA.serviceId}")
|
||||
private String serviceId;
|
||||
|
||||
@Value("${ioTDA.productId}")
|
||||
private String productId;
|
||||
|
||||
public ICredential auth;
|
||||
|
||||
public static IoTDAClient client;
|
||||
|
||||
public void connect() {
|
||||
// 创建认证
|
||||
auth = new BasicCredentials()
|
||||
.withAk(ak)
|
||||
.withSk(sk)
|
||||
// 标准版/企业版需要使用衍生算法,基础版请删除配置"withDerivedPredicate"
|
||||
.withDerivedPredicate(BasicCredentials.DEFAULT_DERIVED_PREDICATE)
|
||||
.withProjectId(projectId);
|
||||
|
||||
// 创建IoTDAClient实例并初始化
|
||||
client = IoTDAClient.newBuilder()
|
||||
.withCredential(auth)
|
||||
// 标准版/企业版:需自行创建Region对象,基础版:请使用IoTDARegion的region对象,如"withRegion(IoTDARegion.CN_NORTH_4)"
|
||||
.withRegion(new Region(REGION_ID, ENDPOINT))
|
||||
// .withRegion(IoTDARegion.CN_NORTH_4)
|
||||
// 配置是否忽略SSL证书校验, 默认不忽略
|
||||
// .withHttpConfig(new HttpConfig().withIgnoreSSLVerification(true))
|
||||
.build();
|
||||
}
|
||||
|
||||
public List<QueryDeviceSimplify> listDevices() {
|
||||
// 实例化请求对象
|
||||
ListDevicesRequest request = new ListDevicesRequest();
|
||||
try {
|
||||
System.out.println("通过SDK下发获取设备列表");
|
||||
// 调用查询设备列表接口
|
||||
ListDevicesResponse response = client.listDevices(request);
|
||||
System.out.println("获取设备列表方法返回结果: " + JsonUtils.toJsonString(response.getDevices()));
|
||||
return response.getDevices();
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
|
||||
public Object deviceShadow(String id) {
|
||||
// 实例化请求对象
|
||||
ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
|
||||
try {
|
||||
request.withDeviceId(id);
|
||||
// request.withInstanceId()
|
||||
List<DeviceShadowData> list = Collections.emptyList();
|
||||
ShowDeviceShadowResponse response = client.showDeviceShadow(request);
|
||||
if (response != null && !CollectionUtils.isEmpty(response.getShadow())) {
|
||||
List<DeviceShadowData> data = response.getShadow();
|
||||
list = data.stream().filter(x -> x.getServiceId().equals(serviceId)).collect(Collectors.toList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(list) && list.get(0).getReported() != null) {
|
||||
return list.get(0).getReported().getProperties();
|
||||
}
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String command(String deviceId, String commandName, Object params) {
|
||||
CreateCommandRequest request = new CreateCommandRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
DeviceCommandRequest body = new DeviceCommandRequest();
|
||||
body.setServiceId(serviceId);
|
||||
body.setCommandName(commandName);
|
||||
body.setParas(params);
|
||||
request.withBody(body);
|
||||
try {
|
||||
CreateCommandResponse response = client.createCommand(request);
|
||||
return response.getCommandId();
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String deleteRule(String ruleId) {
|
||||
DeleteRoutingRuleRequest request = new DeleteRoutingRuleRequest();
|
||||
request.withRuleId(ruleId);
|
||||
try {
|
||||
DeleteRoutingRuleResponse response = client.deleteRoutingRule(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String createRule(String ruleName, String resource, String event) {
|
||||
CreateRoutingRuleRequest request = new CreateRoutingRuleRequest();
|
||||
AddRuleReq body = new AddRuleReq();
|
||||
body.withRuleName(ruleName);
|
||||
RoutingRuleSubject subjectbody = new RoutingRuleSubject();
|
||||
subjectbody.withResource(resource)
|
||||
.withEvent(event);
|
||||
body.withSubject(subjectbody);
|
||||
request.withBody(body);
|
||||
try {
|
||||
CreateRoutingRuleResponse response = client.createRoutingRule(request);
|
||||
if (response != null && !StringUtils.isEmpty(response.getRuleId())) {
|
||||
createRuleAction(response.getRuleId());
|
||||
updateRule(true, response.getRuleId());
|
||||
return response.getRuleId();
|
||||
}
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Boolean updateRule(Boolean b, String ruleId) {
|
||||
UpdateRoutingRuleRequest request = new UpdateRoutingRuleRequest();
|
||||
request.withRuleId(ruleId);
|
||||
UpdateRuleReq body = new UpdateRuleReq();
|
||||
body.withActive(b);
|
||||
request.withBody(body);
|
||||
try {
|
||||
UpdateRoutingRuleResponse response = client.updateRoutingRule(request);
|
||||
return response.getActive();
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<RoutingRule> ruleList() {
|
||||
ListRoutingRulesRequest request = new ListRoutingRulesRequest();
|
||||
try {
|
||||
ListRoutingRulesResponse response = client.listRoutingRules(request);
|
||||
return response.getRules();
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String deleteRuleAction(String actionId) {
|
||||
DeleteRuleActionRequest request = new DeleteRuleActionRequest();
|
||||
request.withActionId(actionId);
|
||||
try {
|
||||
DeleteRuleActionResponse response = client.deleteRuleAction(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String createRuleAction(String ruleId) {
|
||||
CreateRuleActionRequest request = new CreateRuleActionRequest();
|
||||
AddActionReq body = new AddActionReq();
|
||||
HttpForwarding httpForwardingChannelDetail = new HttpForwarding();
|
||||
httpForwardingChannelDetail.withUrl("https://serviceri.satabot.com/iotDA/device/callback");
|
||||
ChannelDetail channelDetailbody = new ChannelDetail();
|
||||
channelDetailbody.withHttpForwarding(httpForwardingChannelDetail);
|
||||
body.withChannelDetail(channelDetailbody);
|
||||
body.withChannel("HTTP_FORWARDING");
|
||||
body.withRuleId(ruleId);
|
||||
request.withBody(body);
|
||||
try {
|
||||
CreateRuleActionResponse response = client.createRuleAction(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<RoutingRuleAction> ruleActionList(String ruleId) {
|
||||
ListRuleActionsRequest request = new ListRuleActionsRequest();
|
||||
request.withRuleId(ruleId);
|
||||
try {
|
||||
ListRuleActionsResponse response = client.listRuleActions(request);
|
||||
return response.getActions();
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public AddDeviceResponse addDevice(String nodeId) {
|
||||
AddDeviceRequest request = new AddDeviceRequest();
|
||||
AddDevice body = new AddDevice();
|
||||
body.withProductId(productId);
|
||||
body.withNodeId(nodeId);
|
||||
request.withBody(body);
|
||||
try {
|
||||
AddDeviceResponse response = client.addDevice(request);
|
||||
return response;
|
||||
} catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String deleteDevice(String id) {
|
||||
DeleteDeviceRequest request = new DeleteDeviceRequest();
|
||||
request.withDeviceId(id);
|
||||
try {
|
||||
DeleteDeviceResponse response = client.deleteDevice(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String updateDevice(String deviceName, String deviceId) {
|
||||
UpdateDeviceRequest request = new UpdateDeviceRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
UpdateDevice body = new UpdateDevice();
|
||||
body.withDeviceName(deviceName);
|
||||
request.withBody(body);
|
||||
try {
|
||||
UpdateDeviceResponse response = client.updateDevice(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String freezeDevice(String deviceId) {
|
||||
FreezeDeviceRequest request = new FreezeDeviceRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
try {
|
||||
FreezeDeviceResponse response = client.freezeDevice(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String unfreezeDevice(String deviceId) {
|
||||
UnfreezeDeviceRequest request = new UnfreezeDeviceRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
try {
|
||||
UnfreezeDeviceResponse response = client.unfreezeDevice(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String createMessage(String deviceId, String json) {
|
||||
CreateMessageRequest request = new CreateMessageRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
DeviceMessageRequest body = new DeviceMessageRequest();
|
||||
body.withMessage(json);
|
||||
request.withBody(body);
|
||||
try {
|
||||
CreateMessageResponse response = client.createMessage(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<DeviceMessage> listDeviceMessages(String deviceId) {
|
||||
ListDeviceMessagesRequest request = new ListDeviceMessagesRequest();
|
||||
request.withDeviceId(deviceId);
|
||||
try {
|
||||
ListDeviceMessagesResponse response = client.listDeviceMessages(request);
|
||||
return response.getMessages();
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String addDeviceGroup(String name) {
|
||||
AddDeviceGroupRequest request = new AddDeviceGroupRequest();
|
||||
AddDeviceGroupDTO body = new AddDeviceGroupDTO();
|
||||
body.withName(name);
|
||||
request.withBody(body);
|
||||
try {
|
||||
AddDeviceGroupResponse response = client.addDeviceGroup(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String manageDeviceGroup(String groupId, String actionId, String deviceId) {
|
||||
CreateOrDeleteDeviceInGroupRequest request = new CreateOrDeleteDeviceInGroupRequest();
|
||||
request.withGroupId(groupId);
|
||||
request.withActionId(actionId);
|
||||
request.withDeviceId(deviceId);
|
||||
try {
|
||||
CreateOrDeleteDeviceInGroupResponse response = client.createOrDeleteDeviceInGroup(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public String deleteDeviceGroup(String groupId) {
|
||||
DeleteDeviceGroupRequest request = new DeleteDeviceGroupRequest();
|
||||
request.withGroupId(groupId);
|
||||
try {
|
||||
DeleteDeviceGroupResponse response = client.deleteDeviceGroup(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<DeviceGroupResponseDTO> listDeviceGroups() {
|
||||
ListDeviceGroupsRequest request = new ListDeviceGroupsRequest();
|
||||
try {
|
||||
ListDeviceGroupsResponse response = client.listDeviceGroups(request);
|
||||
return response.getDeviceGroups();
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<SimplifyDevice> showDevicesInGroup(String groupId) {
|
||||
ShowDevicesInGroupRequest request = new ShowDevicesInGroupRequest();
|
||||
request.withGroupId(groupId);
|
||||
try {
|
||||
ShowDevicesInGroupResponse response = client.showDevicesInGroup(request);
|
||||
return response.getDevices();
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String updateDeviceGroup(String groupId, String name, String description) {
|
||||
UpdateDeviceGroupRequest request = new UpdateDeviceGroupRequest();
|
||||
request.withGroupId(groupId);
|
||||
UpdateDeviceGroupDTO body = new UpdateDeviceGroupDTO();
|
||||
body.withDescription(description);
|
||||
body.withName(name);
|
||||
request.withBody(body);
|
||||
try {
|
||||
UpdateDeviceGroupResponse response = client.updateDeviceGroup(request);
|
||||
System.out.println(response.toString());
|
||||
} catch (ConnectionException | ServiceResponseException | RequestTimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
213
maibu-iotDA/src/main/java/com/maibu/utils/IoTDAMqttClient.java
Normal file
213
maibu-iotDA/src/main/java/com/maibu/utils/IoTDAMqttClient.java
Normal file
@@ -0,0 +1,213 @@
|
||||
package com.maibu.utils;
|
||||
|
||||
import com.fastbee.common.NettyCacheKey;
|
||||
import com.fastbee.common.core.redis.RedisCache;
|
||||
import com.fastbee.common.utils.spring.SpringUtils;
|
||||
import com.fastbee.dto.NettyDevice;
|
||||
import com.fastbee.iot.domain.DeviceRunningStatusHistory;
|
||||
import com.fastbee.iot.domain.DeviceStatusRecordDTO;
|
||||
import com.fastbee.manager.DeviceSessionManager;
|
||||
import com.huaweicloud.sdk.iot.device.IoTDevice;
|
||||
import com.huaweicloud.sdk.iot.device.client.listener.CommandListener;
|
||||
import com.huaweicloud.sdk.iot.device.client.requests.CommandRsp;
|
||||
import com.huaweicloud.sdk.iot.device.client.requests.DeviceMessage;
|
||||
import com.huaweicloud.sdk.iot.device.client.requests.ServiceProperty;
|
||||
import com.huaweicloud.sdk.iot.device.transport.ActionListener;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class IoTDAMqttClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(IoTDAMqttClient.class);
|
||||
|
||||
public String serverIp;
|
||||
// @Value("${ioTDA.deviceId}")
|
||||
// private String deviceId;
|
||||
|
||||
public String secret;
|
||||
|
||||
public String serviceId;
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
public IoTDevice device;
|
||||
|
||||
public String deviceId;
|
||||
public int status = -1;
|
||||
|
||||
private static final RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
|
||||
|
||||
private static final DeviceSessionManager deviceSessionManager = SpringUtils.getBean(DeviceSessionManager.class);
|
||||
|
||||
|
||||
public void judeConnect() throws IOException {
|
||||
String[] s = deviceId.split("_");
|
||||
String nettyDeviceId = s[1];
|
||||
NettyDevice nettyDevice = deviceSessionManager.getDevice(nettyDeviceId);
|
||||
if (nettyDevice == null || nettyDevice.getOnlineStatus() != 1) {
|
||||
if (device != null) {
|
||||
device.getClient().close();
|
||||
device = null;
|
||||
}
|
||||
} else {
|
||||
this.connect(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void connect(boolean isSSL) throws IOException {
|
||||
// 获取证书路径:加载iot平台的ca证书,进行服务端校验,使用sdk默认的ca.jks即可。
|
||||
// URL resource = IoTDAMqttClient.class.getClassLoader().getResource("ca.jks");
|
||||
InputStream inputStream = IoTDAMqttClient.class.getClassLoader().getResourceAsStream("ca.jks");
|
||||
if (inputStream == null) {
|
||||
throw new FileNotFoundException("无法在 classpath 中找到 ca.jks");
|
||||
}
|
||||
|
||||
// 2. 创建临时文件 (这会在服务器硬盘上生成一个真实的文件,例如 /tmp/iot_ca_xxx.jks)
|
||||
// deleteOnExit() 保证程序退出时自动删除,避免垃圾堆积
|
||||
File tempCertFile = File.createTempFile("iot_ca_", ".jks");
|
||||
tempCertFile.deleteOnExit();
|
||||
|
||||
// 3. 将流内容复制到临时文件
|
||||
Files.copy(inputStream, tempCertFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
// 关闭流
|
||||
inputStream.close();
|
||||
|
||||
System.out.println("证书已解压至临时文件: " + tempCertFile.getAbsolutePath());
|
||||
|
||||
// 4. 【关键】使用这个临时文件的路径,而不是原始 resource 的路径
|
||||
// 假设你的 SDK 初始化代码是这样写的,请替换掉原来的 new File(resource.getPath())
|
||||
|
||||
// 原错误代码:
|
||||
// URL resource = IoTDAMqttClient.class.getClassLoader().getResource("ca.jks");
|
||||
// File file = new File(resource.getPath());
|
||||
|
||||
// ✅ 修正后的代码:
|
||||
File file = tempCertFile;
|
||||
|
||||
//例如在iot-device-demo文件 MessageSample.java中修改以下参数
|
||||
String url;
|
||||
if (isSSL) {
|
||||
url = "ssl://" + serverIp + ":" + 8883; //mqtts连接
|
||||
} else {
|
||||
url = "tcp://" + serverIp + ":" + 1883; //mqtt连接
|
||||
}
|
||||
|
||||
device = new IoTDevice(url,
|
||||
deviceId, secret, file);
|
||||
// 设置监听器接收下行命令
|
||||
device.getClient().setCommandListener(new CommandListener() {
|
||||
@Override
|
||||
public void onCommand(String requestId, String serviceId, String commandName, Map<String, Object> paras) {
|
||||
System.out.println("收到命令: serviceId=" + serviceId + ", commandName=" + commandName);
|
||||
System.out.println("命令参数: " + paras.toString());
|
||||
//todo
|
||||
// 处理命令逻辑(示例:打印参数并响应)
|
||||
System.out.println("正在处理命令...");
|
||||
|
||||
// 发送命令响应(必须调用)
|
||||
device.getClient().respondCommand(requestId, new CommandRsp(0)); // 0表示执行成功
|
||||
}
|
||||
});
|
||||
this.status = device.init();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上报json数据,注意serviceId要与Profile中的定义对应
|
||||
*/
|
||||
public void publishMessage() {
|
||||
|
||||
//todo 模拟推送
|
||||
String jsonMsg = "{\"services\":[{\"service_id\":\"BasicData\",\"properties\":{\"luminance\":%s},\"eventTime\":null}]}";
|
||||
String upMsg = String.format(jsonMsg, random.nextInt(100));
|
||||
DeviceMessage message = new DeviceMessage(upMsg);
|
||||
try {
|
||||
device.getClient().reportDeviceMessage(message, new ActionListener() {
|
||||
@Override
|
||||
public void onSuccess(Object context) {
|
||||
logger.info("reportDeviceMessage ok");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Object context, Throwable var2) {
|
||||
logger.error("reportDeviceMessage fail: {}", String.valueOf(var2));
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报json数据,注意serviceId要与Profile中的定义对应
|
||||
*/
|
||||
public void publishProperty() {
|
||||
|
||||
Map<String, Object> json = new HashMap<>();
|
||||
|
||||
String[] s = deviceId.split("_");
|
||||
String nettyDeviceId = s[1];
|
||||
String key = NettyCacheKey.deviceRunningStatusKey + nettyDeviceId;
|
||||
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(key);
|
||||
NettyDevice nettyDevice = deviceSessionManager.getDevice(nettyDeviceId);
|
||||
if (nettyDevice == null || nettyDevice.getOnlineStatus() != 1) {
|
||||
if (device != null) {
|
||||
device.getClient().close();
|
||||
device = null;
|
||||
}
|
||||
} else {
|
||||
if (recordDTO != null && !CollectionUtils.isEmpty(recordDTO.getHistories())) {
|
||||
DeviceRunningStatusHistory history = recordDTO.getHistories().get(recordDTO.getHistories().size() - 1);
|
||||
//按照物模型设置属性
|
||||
json.put("latitude", history.getLatitude());
|
||||
json.put("longitude", history.getLongitude());
|
||||
|
||||
json.put("onlineStatus", nettyDevice.getOnlineStatus());
|
||||
json.put("time", nettyDevice.getLatestStatus() == null ? null : nettyDevice.getLatestStatus().getTime());
|
||||
|
||||
json.put("battery", history.getBattery());
|
||||
json.put("workingArea", history.getWorkingArea());
|
||||
|
||||
json.put("voltage", history.getVoltage());
|
||||
json.put("leftMeasureSpeed", history.getLeftMeasureSpeed());
|
||||
json.put("leftCurrent", history.getLeftCurrent());
|
||||
json.put("rightMeasureSpeed", history.getRightMeasureSpeed());
|
||||
json.put("rightCurrent", history.getRightCurrent());
|
||||
json.put("chipTemp", history.getChipTemp());
|
||||
|
||||
}
|
||||
ServiceProperty serviceProperty = new ServiceProperty();
|
||||
serviceProperty.setProperties(json);
|
||||
serviceProperty.setServiceId(serviceId);//serviceId要和物模型一致
|
||||
|
||||
device.getClient().reportProperties(Arrays.asList(serviceProperty), new ActionListener() {
|
||||
@Override
|
||||
public void onSuccess(Object context) {
|
||||
logger.info("pubMessage success");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Object context, Throwable var2) {
|
||||
logger.error("reportProperties failed{}", var2.toString());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
BIN
maibu-iotDA/src/main/resources/ca.jks
Normal file
BIN
maibu-iotDA/src/main/resources/ca.jks
Normal file
Binary file not shown.
Reference in New Issue
Block a user