dji-cloud-api module add
This commit is contained in:
@@ -60,6 +60,10 @@
|
||||
<tomcat-embed-core.version>10.1.11</tomcat-embed-core.version>
|
||||
<httpclient.version>5.2.1</httpclient.version>
|
||||
<oauth2-oidc-sdk.version>11.7</oauth2-oidc-sdk.version>
|
||||
<dji-cloud-sdk.version>1.3.1</dji-cloud-sdk.version>
|
||||
<okhttp3.version>4.9.1</okhttp3.version>
|
||||
<glassfish-jaxb.version>2.3.3</glassfish-jaxb.version>
|
||||
<javax-jaxb.version>2.3.0</javax-jaxb.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
<?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.zlt</groupId>
|
||||
<artifactId>zlt-business</artifactId>
|
||||
<version>6.0.0</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.central</groupId>
|
||||
<artifactId>cloud-api-center</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.dji</groupId>
|
||||
<artifactId>cloud-sdk</artifactId>
|
||||
<version>${dji-cloud-sdk.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-log-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-db-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-sentinel-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-configuration2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-prometheus</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-configuration</groupId>
|
||||
<artifactId>commons-configuration</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${javax-jaxb.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- no more than 2.3.3-->
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jaxb</groupId>
|
||||
<artifactId>jaxb-runtime</artifactId>
|
||||
<version>${glassfish-jaxb.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-s3</artifactId>
|
||||
<version>1.12.261</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-sts</artifactId>
|
||||
<version>1.12.261</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dom4j</groupId>
|
||||
<artifactId>dom4j</artifactId>
|
||||
<version>2.1.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcpkix-jdk15on</artifactId>
|
||||
<version>1.69</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-core</artifactId>
|
||||
<version>9.0.75</version>
|
||||
<scope>provided</scope> <!-- 通常设置为provided,因为在实际部署时,Servlet容器会提供这个依赖 -->
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@MapperScan("com.central.cloud.api.*.dao")
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
@ComponentScan("com.dji")
|
||||
public class CloudApiSampleApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CloudApiSampleApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.central;
|
||||
|
||||
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
|
||||
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
|
||||
// to see how IntelliJ IDEA suggests fixing it.
|
||||
System.out.printf("Hello and welcome!");
|
||||
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
//TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
|
||||
// for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
|
||||
System.out.println("i = " + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.central.common.error;
|
||||
|
||||
import com.dji.sdk.common.IErrorInfo;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/25
|
||||
*/
|
||||
public enum CommonErrorEnum implements IErrorInfo {
|
||||
|
||||
ILLEGAL_ARGUMENT(200001, "illegal argument"),
|
||||
|
||||
REDIS_DATA_NOT_FOUND(201404, "Redis data does not exist."),
|
||||
|
||||
DEVICE_OFFLINE(212015, "Device is offline."),
|
||||
|
||||
GET_ORGANIZATION_FAILED(210230, "Failed to get organization."),
|
||||
|
||||
DEVICE_BINDING_FAILED(210231, "Failed to bind device."),
|
||||
|
||||
NON_REPEATABLE_BINDING(210232, "The device has been bound to another organization and can't be bound repeatedly."),
|
||||
|
||||
GET_DEVICE_BINDING_STATUS_FAILED(210233, "Failed to get device binding status."),
|
||||
|
||||
SYSTEM_ERROR(600500, "system error"),
|
||||
|
||||
SECRET_INVALID(600100, "secret invalid"),
|
||||
|
||||
NO_TOKEN(600101, "token is null"),
|
||||
|
||||
TOKEN_EXPIRED(600102, "token is expired"),
|
||||
|
||||
TOKEN_INVALID(600103, "token invalid"),
|
||||
|
||||
SIGN_INVALID(600104, "sign invalid");
|
||||
|
||||
private String msg;
|
||||
|
||||
private int code;
|
||||
|
||||
CommonErrorEnum(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return this.msg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import com.auth0.jwt.interfaces.Claim;
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* A custom claim for storing custom information in the token.
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/16
|
||||
* @version 0.1
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
@Slf4j
|
||||
public class CustomClaim {
|
||||
|
||||
/**
|
||||
* The id of the account.
|
||||
*/
|
||||
private String id;
|
||||
|
||||
private String username;
|
||||
|
||||
@JsonAlias("user_type")
|
||||
private Integer userType;
|
||||
|
||||
@JsonAlias("workspace_id")
|
||||
private String workspaceId;
|
||||
|
||||
/**
|
||||
* Convert the custom claim data type to the Map type.
|
||||
* @return map
|
||||
*/
|
||||
public ConcurrentHashMap<String, String> convertToMap() {
|
||||
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(4);
|
||||
try {
|
||||
Field[] declaredFields = this.getClass().getDeclaredFields();
|
||||
for (Field field : declaredFields) {
|
||||
JsonAlias annotation = field.getAnnotation(JsonAlias.class);
|
||||
field.setAccessible(true);
|
||||
// The value of key is named underscore.
|
||||
map.put(annotation != null ? annotation.value()[0] : field.getName(),
|
||||
field.get(this).toString());
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
log.info("CustomClaim converts failed. {}", this.toString());
|
||||
e.printStackTrace();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the data in Map into a custom claim object.
|
||||
* @param claimMap
|
||||
*/
|
||||
public CustomClaim (Map<String, Claim> claimMap) {
|
||||
Field[] declaredFields = this.getClass().getDeclaredFields();
|
||||
for (Field field : declaredFields) {
|
||||
field.setAccessible(true);
|
||||
JsonAlias annotation = field.getAnnotation(JsonAlias.class);
|
||||
|
||||
Claim value = claimMap.get(annotation == null ? field.getName() : annotation.value()[0]);
|
||||
try {
|
||||
Class<?> type = field.getType();
|
||||
if (Integer.class.equals(type)) {
|
||||
field.set(this, Integer.valueOf(value.asString()));
|
||||
continue;
|
||||
}
|
||||
if (String.class.equals(type)) {
|
||||
field.set(this, value.asString());
|
||||
continue;
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
log.info("Claim parses failed. {}", claimMap.toString());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.central.common.util;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.TokenExpiredException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.central.common.model.CustomClaim;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtUtil {
|
||||
|
||||
private static String issuer;
|
||||
|
||||
private static String subject;
|
||||
|
||||
private static long age;
|
||||
|
||||
private static String secret;
|
||||
|
||||
public static Algorithm algorithm;
|
||||
|
||||
@Value("${jwt.issuer: DJI}")
|
||||
private void setIssuer(String issuer) {
|
||||
JwtUtil.issuer = issuer;
|
||||
}
|
||||
|
||||
@Value("${jwt.subject: CloudApiSample}")
|
||||
private void setSubject(String subject) {
|
||||
JwtUtil.subject = subject;
|
||||
}
|
||||
|
||||
@Value("${jwt.age: 86400}")
|
||||
private void setAge(long age) {
|
||||
JwtUtil.age = age * 1000;
|
||||
}
|
||||
|
||||
@Value("${jwt.secret: CloudApiSample}")
|
||||
private void setSecret(String secret) {
|
||||
JwtUtil.secret = secret;
|
||||
setAlgorithm();
|
||||
}
|
||||
|
||||
private void setAlgorithm() {
|
||||
JwtUtil.algorithm = Algorithm.HMAC256(secret);
|
||||
}
|
||||
|
||||
private JwtUtil() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a token based on custom information.
|
||||
* @param claims custom information
|
||||
* @return token
|
||||
*/
|
||||
public static String createToken(Map<String, ?> claims) {
|
||||
return JwtUtil.createToken(claims, age, algorithm, subject, issuer);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param claims
|
||||
* @param age unit: s
|
||||
* @param algorithm
|
||||
* @param subject
|
||||
* @param issuer
|
||||
* @return
|
||||
*/
|
||||
public static String createToken(Map<String, ?> claims, Long age, Algorithm algorithm, String subject, String issuer) {
|
||||
if (Objects.isNull(algorithm)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
Date now = new Date();
|
||||
JWTCreator.Builder builder = JWT.create();
|
||||
// Add custom information to the token's payload segment.
|
||||
claims.forEach((k, v) -> {
|
||||
if (Objects.nonNull(v.getClass().getClassLoader())) {
|
||||
log.error("claim can't be set to a custom object.");
|
||||
return;
|
||||
}
|
||||
if (v instanceof Map) {
|
||||
builder.withClaim(k, (Map) v);
|
||||
} else if (v instanceof List) {
|
||||
builder.withClaim(k, (List) v);
|
||||
} else {
|
||||
builder.withClaim(k, String.valueOf(v));
|
||||
}
|
||||
});
|
||||
|
||||
if (StringUtils.hasText(subject)) {
|
||||
builder.withSubject(subject);
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(issuer)) {
|
||||
builder.withIssuer(issuer);
|
||||
}
|
||||
|
||||
if (Objects.nonNull(age)) {
|
||||
builder.withExpiresAt(new Date(now.getTime() + age));
|
||||
}
|
||||
|
||||
String token = builder
|
||||
.withIssuedAt(now)
|
||||
.withNotBefore(now)
|
||||
.sign(algorithm);
|
||||
log.debug("token created. " + token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the token is valid.
|
||||
* @param token
|
||||
* @return
|
||||
* @throws TokenExpiredException
|
||||
*/
|
||||
public static DecodedJWT verifyToken(String token) {
|
||||
return JWT.require(algorithm).build().verify(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the custom information in the token into a CustomClaim object.
|
||||
* @param token
|
||||
* @return custom claim
|
||||
*/
|
||||
public static Optional<CustomClaim> parseToken(String token) {
|
||||
DecodedJWT jwt;
|
||||
try {
|
||||
jwt = verifyToken(token);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new CustomClaim(jwt.getClaims()));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.central.common.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/10
|
||||
*/
|
||||
@Component
|
||||
public class SpringBeanUtilsTest implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringBeanUtilsTest.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> clazz) {
|
||||
return applicationContext.getBean(clazz);
|
||||
}
|
||||
|
||||
public static Object getBean(String beanName) {
|
||||
return applicationContext.getBean(beanName);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.central.component;
|
||||
|
||||
import com.central.component.redis.RedisConst;
|
||||
import com.central.component.redis.RedisOpsUtils;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.cloudapi.device.DeviceDomainEnum;
|
||||
import com.dji.sdk.common.SDKManager;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/24
|
||||
* @version 0.1
|
||||
*/
|
||||
@Component
|
||||
public class ApplicationBootInitial implements CommandLineRunner {
|
||||
|
||||
@Autowired
|
||||
private IDeviceService deviceService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceRedisService deviceRedisService;
|
||||
|
||||
/**
|
||||
* Subscribe to the devices that exist in the redis when the program starts,
|
||||
* to prevent the data from being different from the pilot side due to program interruptions.
|
||||
* @param args
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
int start = RedisConst.DEVICE_ONLINE_PREFIX.length();
|
||||
|
||||
RedisOpsUtils.getAllKeys(RedisConst.DEVICE_ONLINE_PREFIX + "*")
|
||||
.stream()
|
||||
.map(key -> key.substring(start))
|
||||
.map(deviceRedisService::getDeviceOnline)
|
||||
.map(Optional::get)
|
||||
.filter(device -> DeviceDomainEnum.DRONE != device.getDomain())
|
||||
.forEach(device -> deviceService.subDeviceOnlineSubscribeTopic(
|
||||
SDKManager.registerDevice(device.getDeviceSn(), device.getChildDeviceSn(), device.getDomain(),
|
||||
device.getType(), device.getSubType(), device.getThingVersion(),
|
||||
deviceRedisService.getDeviceOnline(device.getChildDeviceSn()).map(DeviceDTO::getThingVersion).orElse(null))));
|
||||
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.central.component;
|
||||
|
||||
import com.central.common.error.CommonErrorEnum;
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.common.util.JwtUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final String PARAM_TOKEN = "x-auth-token";
|
||||
|
||||
public static final String TOKEN_CLAIM = "customClaim";
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String uri = request.getRequestURI();
|
||||
log.debug("request uri: {}, IP: {}", uri, request.getRemoteAddr());
|
||||
// The options method is passed directly.
|
||||
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
|
||||
response.setStatus(HttpStatus.OK.value());
|
||||
return false;
|
||||
}
|
||||
String token = request.getHeader(PARAM_TOKEN);
|
||||
// Check if the token exists.
|
||||
if (!StringUtils.hasText(token)) {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
log.error(CommonErrorEnum.NO_TOKEN.getMessage());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the current token is valid.
|
||||
Optional<CustomClaim> customClaimOpt = JwtUtil.parseToken(token);
|
||||
if (customClaimOpt.isEmpty()) {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Put the custom data from the token into the request.
|
||||
request.setAttribute(TOKEN_CLAIM, customClaimOpt.get());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
|
||||
// Delete the custom data in the request after the request ends.
|
||||
request.removeAttribute(TOKEN_CLAIM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.central.component;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.central.component.AuthInterceptor.PARAM_TOKEN;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/22
|
||||
*/
|
||||
@Component
|
||||
public class CorsFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Credentials", "true");
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers," +
|
||||
"Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, "+
|
||||
"Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive," +
|
||||
" User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma," + PARAM_TOKEN);
|
||||
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
|
||||
return;
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.central.component;
|
||||
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.2
|
||||
* @date 2021/12/1
|
||||
*/
|
||||
@ControllerAdvice
|
||||
@ResponseBody
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* Please do not return directly like this, there is a risk.
|
||||
* @param e
|
||||
* @return
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public HttpResultResponse exceptionHandler(Exception e) {
|
||||
e.printStackTrace();
|
||||
return HttpResultResponse.error(e.getLocalizedMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(NullPointerException.class)
|
||||
public HttpResultResponse nullPointerExceptionHandler(NullPointerException e) {
|
||||
e.printStackTrace();
|
||||
return HttpResultResponse.error("A null object appeared.");
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
|
||||
public HttpResultResponse methodArgumentNotValidExceptionHandler(BindException e) {
|
||||
e.printStackTrace();
|
||||
return HttpResultResponse.error(e.getFieldError().getField() + e.getFieldError().getDefaultMessage());
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.central.component;
|
||||
|
||||
import com.central.component.redis.RedisConst;
|
||||
import com.central.component.redis.RedisOpsUtils;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.cloudapi.device.DeviceDomainEnum;
|
||||
import com.dji.sdk.mqtt.IMqttTopicService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/24
|
||||
* @version 0.1
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class GlobalScheduleService {
|
||||
|
||||
@Autowired
|
||||
private IDeviceService deviceService;
|
||||
|
||||
@Autowired
|
||||
private IMqttTopicService topicService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
/**
|
||||
* Check the status of the devices every 30 seconds. It is recommended to use cache.
|
||||
*/
|
||||
@Scheduled(initialDelay = 10, fixedRate = 30, timeUnit = TimeUnit.SECONDS)
|
||||
private void deviceStatusListen() {
|
||||
int start = RedisConst.DEVICE_ONLINE_PREFIX.length();
|
||||
|
||||
RedisOpsUtils.getAllKeys(RedisConst.DEVICE_ONLINE_PREFIX + "*").forEach(key -> {
|
||||
long expire = RedisOpsUtils.getExpire(key);
|
||||
if (expire <= 30) {
|
||||
DeviceDTO device = (DeviceDTO) RedisOpsUtils.get(key);
|
||||
if (null == device) {
|
||||
return;
|
||||
}
|
||||
if (DeviceDomainEnum.DRONE == device.getDomain()) {
|
||||
deviceService.subDeviceOffline(key.substring(start));
|
||||
} else {
|
||||
deviceService.gatewayOffline(key.substring(start));
|
||||
}
|
||||
RedisOpsUtils.del(key);
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Subscriptions: {}", Arrays.toString(topicService.getSubscribedTopic()));
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.central.component.mqtt.config;
|
||||
|
||||
import com.dji.sdk.mqtt.ChannelName;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.integration.channel.DirectChannel;
|
||||
import org.springframework.integration.channel.ExecutorChannel;
|
||||
import org.springframework.messaging.MessageChannel;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* Definition classes for all channels
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/10
|
||||
* @version 0.1
|
||||
*/
|
||||
@Configuration
|
||||
public class MqttMessageChannel {
|
||||
|
||||
@Autowired
|
||||
private Executor threadPool;
|
||||
|
||||
@Bean(name = ChannelName.INBOUND)
|
||||
public MessageChannel inboundChannel() {
|
||||
return new ExecutorChannel(threadPool);
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.DEFAULT)
|
||||
public MessageChannel defaultChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_STATUS)
|
||||
public MessageChannel statusChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_STATE)
|
||||
public MessageChannel stateChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_SERVICES_REPLY)
|
||||
public MessageChannel serviceReplyChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_OSD)
|
||||
public MessageChannel osdChannel() {
|
||||
return new ExecutorChannel(threadPool);
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_REQUESTS)
|
||||
public MessageChannel requestsChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_EVENTS)
|
||||
public MessageChannel eventsChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_PROPERTY_SET_REPLY)
|
||||
public MessageChannel propertySetReply() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
@Bean(name = ChannelName.INBOUND_DRC_UP)
|
||||
public MessageChannel drcUp() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package com.central.component.mqtt.config;
|
||||
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.central.common.util.JwtUtil;
|
||||
import com.central.component.mqtt.model.MqttClientOptions;
|
||||
import com.central.component.mqtt.model.MqttProtocolEnum;
|
||||
import com.central.component.mqtt.model.MqttUseEnum;
|
||||
import com.dji.sdk.cloudapi.control.DrcModeMqttBroker;
|
||||
import lombok.Data;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
|
||||
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/10
|
||||
* @version 0.1
|
||||
*/
|
||||
@Configuration
|
||||
@Data
|
||||
@ConfigurationProperties
|
||||
public class MqttPropertyConfiguration {
|
||||
|
||||
private static Map<MqttUseEnum, MqttClientOptions> mqtt;
|
||||
|
||||
public void setMqtt(Map<MqttUseEnum, MqttClientOptions> mqtt) {
|
||||
MqttPropertyConfiguration.mqtt = mqtt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configuration options of the basic link of the mqtt client.
|
||||
* @return
|
||||
*/
|
||||
static MqttClientOptions getBasicClientOptions() {
|
||||
if (!mqtt.containsKey(MqttUseEnum.BASIC)) {
|
||||
throw new Error("Please configure the basic mqtt connection parameters first, otherwise application cannot be started.");
|
||||
}
|
||||
return mqtt.get(MqttUseEnum.BASIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the mqtt address of the basic link.
|
||||
* @return
|
||||
*/
|
||||
public static String getBasicMqttAddress() {
|
||||
return getMqttAddress(getBasicClientOptions());
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice the mqtt address according to the parameters of different clients.
|
||||
* @param options
|
||||
* @return
|
||||
*/
|
||||
private static String getMqttAddress(MqttClientOptions options) {
|
||||
StringBuilder addr = new StringBuilder()
|
||||
.append(options.getProtocol().getProtocolAddr())
|
||||
.append(options.getHost().trim())
|
||||
.append(":")
|
||||
.append(options.getPort());
|
||||
if ((options.getProtocol() == MqttProtocolEnum.WS || options.getProtocol() == MqttProtocolEnum.WSS)
|
||||
&& StringUtils.hasText(options.getPath())) {
|
||||
addr.append(options.getPath());
|
||||
}
|
||||
return addr.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the connection parameters of the mqtt client of the drc link.
|
||||
* @param clientId
|
||||
* @param username
|
||||
* @param age The validity period of the token. unit: s
|
||||
* @param map Custom data added in token.
|
||||
* @return
|
||||
*/
|
||||
public static DrcModeMqttBroker getMqttBrokerWithDrc(String clientId, String username, Long age, Map<String, ?> map) {
|
||||
if (!mqtt.containsKey(MqttUseEnum.DRC)) {
|
||||
throw new RuntimeException("Please configure the drc link parameters of mqtt in the backend configuration file first.");
|
||||
}
|
||||
Algorithm algorithm = JwtUtil.algorithm;
|
||||
|
||||
String token = JwtUtil.createToken(map, age, algorithm, null, null);
|
||||
|
||||
return new DrcModeMqttBroker()
|
||||
.setAddress(getMqttAddress(mqtt.get(MqttUseEnum.DRC)))
|
||||
.setUsername(username)
|
||||
.setClientId(clientId)
|
||||
.setExpireTime(System.currentTimeMillis() / 1000 + age)
|
||||
.setPassword(token)
|
||||
.setEnableTls(false);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public MqttConnectOptions mqttConnectOptions() {
|
||||
MqttClientOptions customizeOptions = getBasicClientOptions();
|
||||
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
|
||||
mqttConnectOptions.setServerURIs(new String[]{ getBasicMqttAddress() });
|
||||
mqttConnectOptions.setUserName(customizeOptions.getUsername());
|
||||
mqttConnectOptions.setPassword(StringUtils.hasText(customizeOptions.getPassword()) ?
|
||||
customizeOptions.getPassword().toCharArray() : new char[0]);
|
||||
mqttConnectOptions.setAutomaticReconnect(true);
|
||||
mqttConnectOptions.setKeepAliveInterval(10);
|
||||
return mqttConnectOptions;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MqttPahoClientFactory mqttClientFactory() {
|
||||
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
|
||||
factory.setConnectionOptions(mqttConnectOptions());
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.central.component.mqtt.model;
|
||||
|
||||
import com.dji.sdk.mqtt.events.EventsDataRequest;
|
||||
import com.dji.sdk.mqtt.events.EventsErrorCode;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.*;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.1
|
||||
* @date 2022/6/9
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class EventsReceiver<T> extends EventsDataRequest<T> {
|
||||
|
||||
private String bid;
|
||||
|
||||
private String sn;
|
||||
|
||||
@Override
|
||||
public EventsErrorCode getResult() {
|
||||
return super.getResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EventsReceiver<T> setResult(EventsErrorCode result) {
|
||||
super.setResult(result);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getOutput() {
|
||||
return super.getOutput();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EventsReceiver<T> setOutput(T output) {
|
||||
super.setOutput(output);
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getBid() {
|
||||
return bid;
|
||||
}
|
||||
|
||||
public EventsReceiver<T> setBid(String bid) {
|
||||
this.bid = bid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSn() {
|
||||
return sn;
|
||||
}
|
||||
|
||||
public EventsReceiver<T> setSn(String sn) {
|
||||
this.sn = sn;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.central.component.mqtt.model;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.1
|
||||
* @date 2022/6/14
|
||||
*/
|
||||
public final class MapKeyConst {
|
||||
|
||||
private MapKeyConst(){
|
||||
|
||||
}
|
||||
|
||||
public static final String ACL = "acl";
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.central.component.mqtt.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/18
|
||||
*/
|
||||
@Data
|
||||
public class MqttClientOptions {
|
||||
|
||||
private MqttProtocolEnum protocol;
|
||||
|
||||
private String host;
|
||||
|
||||
private Integer port;
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
private String clientId;
|
||||
|
||||
private String path;
|
||||
|
||||
/**
|
||||
* The topic to subscribe to immediately when client connects. Only required for basic link.
|
||||
*/
|
||||
private String inboundTopic;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.central.component.mqtt.model;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/18
|
||||
*/
|
||||
@Getter
|
||||
public enum MqttProtocolEnum {
|
||||
|
||||
MQTT("tcp"),
|
||||
|
||||
MQTTS("ssl"),
|
||||
|
||||
WS("ws"),
|
||||
|
||||
WSS("wss");
|
||||
|
||||
String protocol;
|
||||
|
||||
MqttProtocolEnum(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public String getProtocolAddr() {
|
||||
return protocol + "://";
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.component.mqtt.model;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/18
|
||||
*/
|
||||
public enum MqttUseEnum {
|
||||
|
||||
/**
|
||||
* The broker is used for basic link.
|
||||
*/
|
||||
BASIC,
|
||||
|
||||
/**
|
||||
* This broker is used for the drc link.
|
||||
*/
|
||||
DRC
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.central.component.mybatis;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.3
|
||||
* @date 2021/12/22
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfiguration {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// select database
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.central.component.mybatis;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Automatic filling for set values
|
||||
*/
|
||||
@Component
|
||||
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
/**
|
||||
* Automatic filling when inserting into the database.
|
||||
* @param metaObject
|
||||
*/
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createTime", Long.class,
|
||||
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
this.strictInsertFill(metaObject, "updateTime", Long.class,
|
||||
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatic filling when updating the data.
|
||||
* @param metaObject
|
||||
*/
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictUpdateFill(metaObject, "updateTime", Long.class,
|
||||
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.central.component.oss.model;
|
||||
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.2
|
||||
* @date 2021/12/9
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "oss")
|
||||
@Component
|
||||
public class OssConfiguration {
|
||||
|
||||
/**
|
||||
* @see OssTypeEnum
|
||||
*/
|
||||
public static OssTypeEnum provider;
|
||||
|
||||
/**
|
||||
* Whether to use the object storage service.
|
||||
*/
|
||||
public static boolean enable;
|
||||
|
||||
/**
|
||||
* The protocol needs to be included at the beginning of the address.
|
||||
*/
|
||||
public static String endpoint;
|
||||
|
||||
public static String accessKey;
|
||||
|
||||
public static String secretKey;
|
||||
|
||||
public static String region;
|
||||
|
||||
public static Long expire;
|
||||
|
||||
public static String roleSessionName;
|
||||
|
||||
public static String roleArn;
|
||||
|
||||
public static String bucket;
|
||||
|
||||
public static String objectDirPrefix;
|
||||
|
||||
public void setProvider(OssTypeEnum provider) {
|
||||
OssConfiguration.provider = provider;
|
||||
}
|
||||
|
||||
public void setEnable(boolean enable) {
|
||||
OssConfiguration.enable = enable;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
OssConfiguration.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public void setAccessKey(String accessKey) {
|
||||
OssConfiguration.accessKey = accessKey;
|
||||
}
|
||||
|
||||
public void setSecretKey(String secretKey) {
|
||||
OssConfiguration.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public void setRegion(String region) {
|
||||
OssConfiguration.region = region;
|
||||
}
|
||||
|
||||
public void setExpire(Long expire) {
|
||||
OssConfiguration.expire = expire;
|
||||
}
|
||||
|
||||
public void setRoleSessionName(String roleSessionName) {
|
||||
OssConfiguration.roleSessionName = roleSessionName;
|
||||
}
|
||||
|
||||
public void setRoleArn(String roleArn) {
|
||||
OssConfiguration.roleArn = roleArn;
|
||||
}
|
||||
|
||||
public void setBucket(String bucket) {
|
||||
OssConfiguration.bucket = bucket;
|
||||
}
|
||||
|
||||
public void setObjectDirPrefix(String objectDirPrefix) {
|
||||
OssConfiguration.objectDirPrefix = objectDirPrefix;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.central.component.oss.service;
|
||||
|
||||
import com.dji.sdk.cloudapi.storage.CredentialsToken;
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.3
|
||||
* @date 2021/12/23
|
||||
*/
|
||||
public interface IOssService {
|
||||
|
||||
OssTypeEnum getOssType();
|
||||
|
||||
/**
|
||||
* Get temporary credentials.
|
||||
* @return
|
||||
*/
|
||||
CredentialsToken getCredentials();
|
||||
|
||||
/**
|
||||
* Get the address of the object based on the bucket name and the object name.
|
||||
* @param bucket bucket name
|
||||
* @param objectKey object name
|
||||
* @return download link
|
||||
*/
|
||||
URL getObjectUrl(String bucket, String objectKey);
|
||||
|
||||
/**
|
||||
* Deletes the object in the storage bucket.
|
||||
* @param bucket
|
||||
* @param objectKey
|
||||
* @return
|
||||
*/
|
||||
Boolean deleteObject(String bucket, String objectKey);
|
||||
|
||||
/**
|
||||
* Get the contents of an object.
|
||||
* @param bucket
|
||||
* @param objectKey
|
||||
* @return
|
||||
*/
|
||||
InputStream getObject(String bucket, String objectKey);
|
||||
|
||||
void putObject(String bucket, String objectKey, InputStream input);
|
||||
|
||||
void createClient();
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package com.central.component.oss.service.impl;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.OSSException;
|
||||
import com.aliyun.oss.model.ObjectMetadata;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.aliyun.oss.model.PutObjectResult;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
|
||||
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
|
||||
import com.central.component.oss.model.OssConfiguration;
|
||||
import com.central.component.oss.service.IOssService;
|
||||
import com.dji.sdk.cloudapi.storage.CredentialsToken;
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.3
|
||||
* @date 2021/12/23
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class AliyunOssServiceImpl implements IOssService {
|
||||
|
||||
private OSS ossClient;
|
||||
|
||||
@Override
|
||||
public OssTypeEnum getOssType() {
|
||||
return OssTypeEnum.ALIYUN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CredentialsToken getCredentials() {
|
||||
|
||||
try {
|
||||
DefaultProfile profile = DefaultProfile.getProfile(
|
||||
OssConfiguration.region, OssConfiguration.accessKey, OssConfiguration.secretKey);
|
||||
IAcsClient client = new DefaultAcsClient(profile);
|
||||
|
||||
AssumeRoleRequest request = new AssumeRoleRequest();
|
||||
request.setDurationSeconds(OssConfiguration.expire);
|
||||
request.setRoleArn(OssConfiguration.roleArn);
|
||||
request.setRoleSessionName(OssConfiguration.roleSessionName);
|
||||
|
||||
AssumeRoleResponse.Credentials response = client.getAcsResponse(request).getCredentials();
|
||||
return new CredentialsToken(response.getAccessKeyId(), response.getAccessKeySecret(), response.getSecurityToken(), OssConfiguration.expire);
|
||||
|
||||
} catch (ClientException e) {
|
||||
log.debug("Failed to obtain sts.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getObjectUrl(String bucket, String objectKey) {
|
||||
// First check if the object can be fetched.
|
||||
boolean isExist = ossClient.doesObjectExist(bucket, objectKey);
|
||||
if (!isExist) {
|
||||
throw new OSSException("The object does not exist.");
|
||||
}
|
||||
|
||||
return ossClient.generatePresignedUrl(bucket, objectKey,
|
||||
new Date(System.currentTimeMillis() + OssConfiguration.expire * 1000));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteObject(String bucket, String objectKey) {
|
||||
if (!ossClient.doesObjectExist(bucket, objectKey)) {
|
||||
return true;
|
||||
}
|
||||
ossClient.deleteObject(bucket, objectKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getObject(String bucket, String objectKey) {
|
||||
return ossClient.getObject(bucket, objectKey).getObjectContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putObject(String bucket, String objectKey, InputStream input) {
|
||||
if (ossClient.doesObjectExist(bucket, objectKey)) {
|
||||
throw new RuntimeException("The filename already exists.");
|
||||
}
|
||||
PutObjectResult objectResult = ossClient.putObject(new PutObjectRequest(bucket, objectKey, input, new ObjectMetadata()));
|
||||
log.info("Upload FlighttaskCreateFile: {}", objectResult.getETag());
|
||||
}
|
||||
|
||||
public void createClient() {
|
||||
if (Objects.nonNull(this.ossClient)) {
|
||||
return;
|
||||
}
|
||||
this.ossClient = new OSSClientBuilder()
|
||||
.build(OssConfiguration.endpoint, OssConfiguration.accessKey, OssConfiguration.secretKey);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.central.component.oss.service.impl;
|
||||
|
||||
import com.amazonaws.HttpMethod;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.*;
|
||||
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
|
||||
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
|
||||
import com.amazonaws.services.securitytoken.model.AssumeRoleRequest;
|
||||
import com.amazonaws.services.securitytoken.model.AssumeRoleResult;
|
||||
import com.amazonaws.services.securitytoken.model.Credentials;
|
||||
import com.central.component.AuthInterceptor;
|
||||
import com.central.component.oss.model.OssConfiguration;
|
||||
import com.central.component.oss.service.IOssService;
|
||||
import com.dji.sdk.cloudapi.storage.CredentialsToken;
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/27
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AmazonS3ServiceImpl implements IOssService {
|
||||
|
||||
private AmazonS3 client;
|
||||
|
||||
@Override
|
||||
public OssTypeEnum getOssType() {
|
||||
return OssTypeEnum.AWS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CredentialsToken getCredentials() {
|
||||
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(
|
||||
new BasicAWSCredentials(OssConfiguration.accessKey, OssConfiguration.secretKey)))
|
||||
.withRegion(OssConfiguration.region).build();
|
||||
|
||||
AssumeRoleRequest request = new AssumeRoleRequest()
|
||||
.withRoleArn(OssConfiguration.roleArn)
|
||||
.withRoleSessionName(OssConfiguration.roleSessionName)
|
||||
.withDurationSeconds(Math.toIntExact(OssConfiguration.expire));
|
||||
AssumeRoleResult result = stsClient.assumeRole(request);
|
||||
Credentials credentials = result.getCredentials();
|
||||
return new CredentialsToken(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
|
||||
credentials.getSessionToken(), (credentials.getExpiration().getTime() - System.currentTimeMillis()) / 1000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getObjectUrl(String bucket, String objectKey) {
|
||||
return client.generatePresignedUrl(bucket, objectKey,
|
||||
new Date(System.currentTimeMillis() + OssConfiguration.expire * 1000), HttpMethod.GET);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteObject(String bucket, String objectKey) {
|
||||
if (!client.doesObjectExist(bucket, objectKey)) {
|
||||
return true;
|
||||
}
|
||||
client.deleteObject(bucket, objectKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
public InputStream getObject(String bucket, String objectKey) {
|
||||
return client.getObject(bucket, objectKey).getObjectContent().getDelegateStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putObject(String bucket, String objectKey, InputStream input) {
|
||||
if (client.doesObjectExist(bucket, objectKey)) {
|
||||
throw new RuntimeException("The filename already exists.");
|
||||
}
|
||||
PutObjectResult objectResult = client.putObject(new PutObjectRequest(bucket, objectKey, input, new ObjectMetadata()));
|
||||
log.info("Upload FlighttaskCreateFile: {}", objectResult.toString());
|
||||
}
|
||||
|
||||
public void createClient() {
|
||||
if (Objects.nonNull(this.client)) {
|
||||
return;
|
||||
}
|
||||
this.client = AmazonS3ClientBuilder.standard()
|
||||
.withCredentials(
|
||||
new AWSStaticCredentialsProvider(
|
||||
new BasicAWSCredentials(OssConfiguration.accessKey, OssConfiguration.secretKey)))
|
||||
.withRegion(OssConfiguration.region)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuring cross-origin resource sharing
|
||||
*/
|
||||
@PostConstruct
|
||||
private void configCORS() {
|
||||
if (!OssConfiguration.enable || !OssTypeEnum.AWS.getType().equals(OssConfiguration.provider)) {
|
||||
return;
|
||||
}
|
||||
List<CORSRule.AllowedMethods> allowedMethods = new ArrayList<>();
|
||||
allowedMethods.add(CORSRule.AllowedMethods.GET);
|
||||
allowedMethods.add(CORSRule.AllowedMethods.POST);
|
||||
allowedMethods.add(CORSRule.AllowedMethods.DELETE);
|
||||
|
||||
CORSRule rule = new CORSRule()
|
||||
.withId("CORSAccessRule")
|
||||
.withAllowedOrigins(List.of("*"))
|
||||
.withAllowedHeaders(List.of(AuthInterceptor.PARAM_TOKEN))
|
||||
.withAllowedMethods(allowedMethods);
|
||||
|
||||
client.setBucketCrossOriginConfiguration(OssConfiguration.bucket,
|
||||
new BucketCrossOriginConfiguration().withRules(rule));
|
||||
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.central.component.oss.service.impl;
|
||||
|
||||
import com.central.component.oss.model.OssConfiguration;
|
||||
import com.central.component.oss.service.IOssService;
|
||||
import com.dji.sdk.cloudapi.storage.CredentialsToken;
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
import io.minio.*;
|
||||
import io.minio.credentials.AssumeRoleProvider;
|
||||
import io.minio.credentials.Credentials;
|
||||
import io.minio.errors.*;
|
||||
import io.minio.http.Method;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.3
|
||||
* @date 2021/12/23
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class MinIOServiceImpl implements IOssService {
|
||||
|
||||
private MinioClient client;
|
||||
|
||||
@Override
|
||||
public OssTypeEnum getOssType() {
|
||||
return OssTypeEnum.MINIO;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CredentialsToken getCredentials() {
|
||||
try {
|
||||
AssumeRoleProvider provider = new AssumeRoleProvider(OssConfiguration.endpoint, OssConfiguration.accessKey,
|
||||
OssConfiguration.secretKey, Math.toIntExact(OssConfiguration.expire),
|
||||
null, OssConfiguration.region, null, null, null, null);
|
||||
Credentials credential = provider.fetch();
|
||||
return new CredentialsToken(credential.accessKey(), credential.secretKey(), credential.sessionToken(), OssConfiguration.expire);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
log.debug("Failed to obtain sts.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getObjectUrl(String bucket, String objectKey) {
|
||||
try {
|
||||
return new URL(
|
||||
client.getPresignedObjectUrl(
|
||||
GetPresignedObjectUrlArgs.builder()
|
||||
.method(Method.GET)
|
||||
.bucket(bucket)
|
||||
.object(objectKey)
|
||||
.expiry(Math.toIntExact(OssConfiguration.expire))
|
||||
.build()));
|
||||
} catch (ErrorResponseException | InsufficientDataException | InternalException |
|
||||
InvalidKeyException | InvalidResponseException | IOException |
|
||||
NoSuchAlgorithmException | XmlParserException | ServerException e) {
|
||||
throw new RuntimeException("The file does not exist on the OssConfiguration.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteObject(String bucket, String objectKey) {
|
||||
try {
|
||||
client.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectKey).build());
|
||||
} catch (MinioException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
|
||||
log.error("Failed to delete file.");
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getObject(String bucket, String objectKey) {
|
||||
try {
|
||||
GetObjectResponse object = client.getObject(GetObjectArgs.builder().bucket(bucket).object(objectKey).build());
|
||||
return new ByteArrayInputStream(object.readAllBytes());
|
||||
} catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return InputStream.nullInputStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putObject(String bucket, String objectKey, InputStream input) {
|
||||
try {
|
||||
client.statObject(StatObjectArgs.builder().bucket(bucket).object(objectKey).build());
|
||||
throw new RuntimeException("The filename already exists.");
|
||||
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
|
||||
log.info("The file does not exist, start uploading.");
|
||||
try {
|
||||
ObjectWriteResponse response = client.putObject(
|
||||
PutObjectArgs.builder().bucket(bucket).object(objectKey).stream(input, input.available(), 0).build());
|
||||
log.info("Upload FlighttaskCreateFile: {}", response.etag());
|
||||
} catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException ex) {
|
||||
log.error("Failed to upload FlighttaskCreateFile {}.", objectKey);
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void createClient() {
|
||||
if (Objects.nonNull(this.client)) {
|
||||
return;
|
||||
}
|
||||
this.client = MinioClient.builder()
|
||||
.endpoint(OssConfiguration.endpoint)
|
||||
.credentials(OssConfiguration.accessKey, OssConfiguration.secretKey)
|
||||
.region(OssConfiguration.region)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.central.component.oss.service.impl;
|
||||
|
||||
import com.central.component.oss.model.OssConfiguration;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.1
|
||||
* @date 2022/6/20
|
||||
*/
|
||||
@Component
|
||||
@Aspect
|
||||
public class OssAspectHandler {
|
||||
|
||||
@Autowired
|
||||
private OssServiceContext ossServiceContext;
|
||||
|
||||
@Before("execution(public * com.central.component.oss.service.impl.OssServiceContext.*(..))")
|
||||
public void before() {
|
||||
if (!OssConfiguration.enable) {
|
||||
throw new IllegalArgumentException("Please enable OssConfiguration.");
|
||||
}
|
||||
if (this.ossServiceContext.getOssService() == null) {
|
||||
throw new IllegalArgumentException("Please check the OssConfiguration configuration.");
|
||||
}
|
||||
this.ossServiceContext.createClient();
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.central.component.oss.service.impl;
|
||||
|
||||
import com.central.component.oss.model.OssConfiguration;
|
||||
import com.central.component.oss.service.IOssService;
|
||||
import com.dji.sdk.cloudapi.storage.CredentialsToken;
|
||||
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/5/30
|
||||
*/
|
||||
@Service
|
||||
public class OssServiceContext {
|
||||
|
||||
private IOssService ossService;
|
||||
|
||||
@Autowired
|
||||
public OssServiceContext(List<IOssService> ossServices, OssConfiguration configuration) {
|
||||
if (!OssConfiguration.enable) {
|
||||
return;
|
||||
}
|
||||
this.ossService = ossServices.stream()
|
||||
.filter(ossService -> ossService.getOssType() == OssConfiguration.provider)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Oss provider is illegal. Optional: " +
|
||||
Arrays.toString(Arrays.stream(OssTypeEnum.values()).map(OssTypeEnum::getType).toArray())));
|
||||
}
|
||||
|
||||
IOssService getOssService() {
|
||||
return this.ossService;
|
||||
}
|
||||
|
||||
public CredentialsToken getCredentials() {
|
||||
return this.ossService.getCredentials();
|
||||
}
|
||||
|
||||
public URL getObjectUrl(String bucket, String objectKey) {
|
||||
if (!StringUtils.hasText(bucket) || !StringUtils.hasText(objectKey)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
return this.ossService.getObjectUrl(bucket, objectKey);
|
||||
}
|
||||
|
||||
public Boolean deleteObject(String bucket, String objectKey) {
|
||||
return this.ossService.deleteObject(bucket, objectKey);
|
||||
}
|
||||
|
||||
public InputStream getObject(String bucket, String objectKey) {
|
||||
return this.ossService.getObject(bucket, objectKey);
|
||||
}
|
||||
|
||||
public void putObject(String bucket, String objectKey, InputStream stream) {
|
||||
this.ossService.putObject(bucket, objectKey, stream);
|
||||
}
|
||||
|
||||
void createClient() {
|
||||
this.ossService.createClient();
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.central.component.redis;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/19
|
||||
*/
|
||||
@Configuration
|
||||
@EnableRedisRepositories
|
||||
public class RedisConfiguration {
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setConnectionFactory(factory);
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JavaTimeModule timeModule = new JavaTimeModule();
|
||||
timeModule.addDeserializer(LocalDateTime.class,
|
||||
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
timeModule.addSerializer(LocalDateTime.class,
|
||||
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
objectMapper.disable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS);
|
||||
objectMapper.registerModules(timeModule);
|
||||
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
|
||||
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
|
||||
|
||||
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
|
||||
|
||||
StringRedisSerializer serializer = new StringRedisSerializer();
|
||||
redisTemplate.setKeySerializer(serializer);
|
||||
redisTemplate.setHashKeySerializer(serializer);
|
||||
|
||||
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
|
||||
redisTemplate.setValueSerializer(jsonRedisSerializer);
|
||||
redisTemplate.setHashValueSerializer(jsonRedisSerializer);
|
||||
redisTemplate.afterPropertiesSet();
|
||||
return redisTemplate;
|
||||
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.central.component.redis;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/21
|
||||
*/
|
||||
public final class RedisConst {
|
||||
|
||||
public static final int WAYLINE_JOB_BLOCK_TIME = 600;
|
||||
|
||||
private RedisConst() {
|
||||
|
||||
}
|
||||
|
||||
public static final String DELIMITER = ":";
|
||||
|
||||
public static final Integer DEVICE_ALIVE_SECOND = 60;
|
||||
|
||||
public static final Integer WEBSOCKET_ALIVE_SECOND = 60 * 60 * 24;
|
||||
|
||||
public static final String DEVICE_ONLINE_PREFIX = "online" + DELIMITER;
|
||||
|
||||
public static final String WEBSOCKET_PREFIX = "webSocket" + DELIMITER;
|
||||
|
||||
public static final String WEBSOCKET_ALL = WEBSOCKET_PREFIX + "all";
|
||||
|
||||
public static final String HMS_PREFIX = "hms" + DELIMITER;
|
||||
|
||||
public static final String FIRMWARE_UPGRADING_PREFIX = "upgrading" + DELIMITER;
|
||||
|
||||
public static final String STATE_PAYLOAD_PREFIX = "payload" + DELIMITER;
|
||||
|
||||
public static final String LOGS_FILE_PREFIX = "logs_file" + DELIMITER;
|
||||
|
||||
public static final String WAYLINE_JOB_TIMED_EXECUTE = "wayline_job_timed_execute";
|
||||
|
||||
public static final String WAYLINE_JOB_CONDITION_PREPARE = "wayline_job_condition_prepare";
|
||||
|
||||
public static final String WAYLINE_JOB_CONDITION_PREFIX = WAYLINE_JOB_CONDITION_PREPARE + DELIMITER;
|
||||
|
||||
public static final String WAYLINE_JOB_BLOCK_PREFIX = "wayline_job_block" + DELIMITER;
|
||||
|
||||
public static final String WAYLINE_JOB_RUNNING_PREFIX = "wayline_job_running" + DELIMITER;
|
||||
|
||||
public static final String WAYLINE_JOB_PAUSED_PREFIX = "wayline_job_paused" + DELIMITER;
|
||||
|
||||
public static final String OSD_PREFIX = "osd" + DELIMITER;
|
||||
|
||||
public static final String MEDIA_FILE_PREFIX = "media_file" + DELIMITER;
|
||||
|
||||
public static final String MEDIA_HIGHEST_PRIORITY_PREFIX = "media_highest_priority" + DELIMITER;
|
||||
|
||||
public static final String LIVE_CAPACITY = "live_capacity";
|
||||
|
||||
public static final String DRC_PREFIX = "drc" + DELIMITER;
|
||||
|
||||
public static final Integer DRC_MODE_ALIVE_SECOND = 3600;
|
||||
|
||||
public static final String MQTT_ACL_PREFIX = "mqtt_acl" + DELIMITER;
|
||||
|
||||
public static final String FILE_UPLOADING_PREFIX = "file_uploading" + DELIMITER;
|
||||
|
||||
public static final String DRONE_CONTROL_PREFiX = "control_source" + DELIMITER;
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package com.central.component.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/19
|
||||
*/
|
||||
@Component
|
||||
public class RedisOpsUtils {
|
||||
|
||||
private static RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Autowired
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
RedisOpsUtils.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* HSET
|
||||
* @param key
|
||||
* @param field
|
||||
* @param value
|
||||
*/
|
||||
public static void hashSet(String key, String field, Object value) {
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* HGET
|
||||
* @param key
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public static Object hashGet(String key, String field) {
|
||||
return redisTemplate.opsForHash().get(key, field);
|
||||
}
|
||||
|
||||
/**
|
||||
* HKEYS
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Set<Object> hashKeys(String key) {
|
||||
return redisTemplate.opsForHash().keys(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* HEXISTS
|
||||
* @param key
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public static boolean hashCheck(String key, String field) {
|
||||
return redisTemplate.opsForHash().hasKey(key, field);
|
||||
}
|
||||
|
||||
/**
|
||||
* HDEL
|
||||
* @param key
|
||||
* @param fields
|
||||
* @return
|
||||
*/
|
||||
public static boolean hashDel(String key, Object[] fields) {
|
||||
return redisTemplate.opsForHash().delete(key, fields) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* HLEN
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static long hashLen(String key) {
|
||||
return redisTemplate.opsForHash().size(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* EXPIRE
|
||||
* @param key
|
||||
* @param timeout
|
||||
* @return
|
||||
*/
|
||||
public static boolean expireKey(String key, long timeout) {
|
||||
return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* SET
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void set(String key, Object value) {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String key) {
|
||||
return redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* SETEX
|
||||
* @param key
|
||||
* @param value
|
||||
* @param expire
|
||||
*/
|
||||
public static void setWithExpire(String key, Object value, long expire) {
|
||||
redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* TTL
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static long getExpire(String key) {
|
||||
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* EXISTS
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean checkExist(String key) {
|
||||
return redisTemplate.hasKey(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEL
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean del(String key) {
|
||||
return RedisOpsUtils.checkExist(key) && redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* KEYS
|
||||
* @param pattern
|
||||
* @return
|
||||
*/
|
||||
public static Set<String> getAllKeys(String pattern) {
|
||||
return redisTemplate.keys(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* RPUSH
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void listRPush(String key, Object... value) {
|
||||
if (value.length == 0) {
|
||||
return;
|
||||
}
|
||||
for (Object val : value) {
|
||||
redisTemplate.opsForList().rightPush(key, val);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* LRANGE
|
||||
* @param key
|
||||
* @param start
|
||||
* @param end
|
||||
* @return
|
||||
*/
|
||||
public static List<Object> listGet(String key, long start, long end) {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* LRANGE
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static List<Object> listGetAll(String key) {
|
||||
return redisTemplate.opsForList().range(key, 0, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* LLen
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Long listLen(String key) {
|
||||
return redisTemplate.opsForList().size(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZADD
|
||||
* @param key
|
||||
* @param value
|
||||
* @param score
|
||||
*/
|
||||
public static Boolean zAdd(String key, Object value, double score) {
|
||||
return redisTemplate.opsForZSet().add(key, value, score);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZREM
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static Boolean zRemove(String key, Object... value) {
|
||||
return redisTemplate.opsForZSet().remove(key, value) > 0;
|
||||
}
|
||||
/**
|
||||
* ZRANGE
|
||||
* @param key
|
||||
* @param start
|
||||
* @param end
|
||||
* @return
|
||||
*/
|
||||
public static Set<Object> zRange(String key, long start, long end) {
|
||||
return redisTemplate.opsForZSet().range(key, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZRANGE
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object zGetMin(String key) {
|
||||
Set<Object> objects = zRange(key, 0, 0);
|
||||
if (CollectionUtils.isEmpty(objects)) {
|
||||
return null;
|
||||
}
|
||||
return objects.iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* ZSCORE
|
||||
* @param key
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public static Double zScore(String key, Object value) {
|
||||
return redisTemplate.opsForZSet().score(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* ZINCRBY
|
||||
* @param key
|
||||
* @param value
|
||||
* @param delta
|
||||
*/
|
||||
public static Double zIncrement(String key, Object value, double delta) {
|
||||
return redisTemplate.opsForZSet().incrementScore(key, value, delta);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.central.component.websocket.config;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.common.util.JwtUtil;
|
||||
import com.central.component.AuthInterceptor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.security.Principal;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/16
|
||||
* @version 0.1
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuthPrincipalHandler extends DefaultHandshakeHandler {
|
||||
|
||||
@Override
|
||||
protected boolean isValidOrigin(ServerHttpRequest request) {
|
||||
|
||||
if (request instanceof ServletServerHttpRequest) {
|
||||
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
|
||||
String token = servletRequest.getParameter(AuthInterceptor.PARAM_TOKEN);
|
||||
|
||||
if (!StringUtils.hasText(token)) {
|
||||
return false;
|
||||
}
|
||||
log.debug("token:" + token);
|
||||
Optional<CustomClaim> customClaim = JwtUtil.parseToken(token);
|
||||
if (customClaim.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
servletRequest.setAttribute(AuthInterceptor.TOKEN_CLAIM, customClaim.get());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The principal's name: {workspaceId}/{userType}/{userId}
|
||||
* @param request
|
||||
* @param wsHandler
|
||||
* @param attributes
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
|
||||
if (request instanceof ServletServerHttpRequest) {
|
||||
|
||||
// get the custom claim
|
||||
CustomClaim claim = (CustomClaim) ((ServletServerHttpRequest) request).getServletRequest()
|
||||
.getAttribute(AuthInterceptor.TOKEN_CLAIM);
|
||||
|
||||
return () -> claim.getWorkspaceId() + "/" + claim.getUserType() + "/" + claim.getId();
|
||||
}
|
||||
return () -> null;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.component.websocket.config;
|
||||
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/24
|
||||
*/
|
||||
public class MyConcurrentWebSocketSession extends ConcurrentWebSocketSessionDecorator {
|
||||
|
||||
private static final int SEND_BUFFER_SIZE_LIMIT = 1024 * 1024;
|
||||
|
||||
private static final int SEND_TIME_LIMIT = 1000;
|
||||
|
||||
private MyConcurrentWebSocketSession(WebSocketSession delegate, int sendTimeLimit, int bufferSizeLimit) {
|
||||
super(delegate, sendTimeLimit, bufferSizeLimit);
|
||||
}
|
||||
|
||||
MyConcurrentWebSocketSession(WebSocketSession delegate) {
|
||||
this(delegate, SEND_TIME_LIMIT, SEND_BUFFER_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.central.component.websocket.config;
|
||||
|
||||
import com.central.component.websocket.service.IWebSocketManageService;
|
||||
import com.dji.sdk.websocket.WebSocketDefaultFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/16
|
||||
* @version 0.1
|
||||
*/
|
||||
@Component
|
||||
@Primary
|
||||
public class MyWebSocketFactory extends WebSocketDefaultFactory {
|
||||
|
||||
@Autowired
|
||||
private IWebSocketManageService webSocketManageService;
|
||||
|
||||
@Override
|
||||
public WebSocketHandler decorate(WebSocketHandler handler) {
|
||||
return new MyWebSocketHandler(handler, webSocketManageService);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.central.component.websocket.config;
|
||||
|
||||
import com.central.component.websocket.service.IWebSocketManageService;
|
||||
import com.dji.sdk.websocket.WebSocketDefaultHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.WebSocketMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/16
|
||||
* @version 0.1
|
||||
*/
|
||||
@Slf4j
|
||||
public class MyWebSocketHandler extends WebSocketDefaultHandler {
|
||||
|
||||
private IWebSocketManageService webSocketManageService;
|
||||
|
||||
MyWebSocketHandler(WebSocketHandler delegate, IWebSocketManageService webSocketManageService) {
|
||||
super(delegate);
|
||||
this.webSocketManageService = webSocketManageService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||
Principal principal = session.getPrincipal();
|
||||
if (StringUtils.hasText(principal.getName())) {
|
||||
webSocketManageService.put(principal.getName(), new MyConcurrentWebSocketSession(session));
|
||||
log.debug("{} is connected. ID: {}. WebSocketSession[current count: {}]",
|
||||
principal.getName(), session.getId(), webSocketManageService.getConnectedCount());
|
||||
return;
|
||||
}
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
|
||||
Principal principal = session.getPrincipal();
|
||||
if (StringUtils.hasText(principal.getName())) {
|
||||
webSocketManageService.remove(principal.getName(), session.getId());
|
||||
log.debug("{} is disconnected. ID: {}. WebSocketSession[current count: {}]",
|
||||
principal.getName(), session.getId(), webSocketManageService.getConnectedCount());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
|
||||
log.debug("received message: {}", message.getPayload());
|
||||
}
|
||||
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.central.component.websocket.model;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.1
|
||||
* @date 2021/11/26
|
||||
*/
|
||||
public enum BizCodeEnum {
|
||||
|
||||
DEVICE_ONLINE("device_online"),
|
||||
|
||||
DEVICE_OFFLINE("device_offline"),
|
||||
|
||||
DEVICE_UPDATE_TOPO("device_update_topo"),
|
||||
|
||||
DEVICE_OSD("device_osd"),
|
||||
|
||||
RC_OSD("gateway_osd"),
|
||||
|
||||
DOCK_OSD("dock_osd"),
|
||||
|
||||
MAP_ELEMENT_CREATE("map_element_create"),
|
||||
|
||||
MAP_ELEMENT_UPDATE("map_element_update"),
|
||||
|
||||
MAP_ELEMENT_DELETE("map_element_delete"),
|
||||
|
||||
MAP_GROUP_REFRESH("map_group_refresh"),
|
||||
|
||||
FLIGHT_TASK_PROGRESS("flighttask_progress"),
|
||||
|
||||
DEVICE_HMS("device_hms"),
|
||||
|
||||
DEVICE_REBOOT("device_reboot"),
|
||||
|
||||
DRONE_OPEN("drone_open"),
|
||||
|
||||
DRONE_CLOSE("drone_close"),
|
||||
|
||||
DEVICE_CHECK("device_check"),
|
||||
|
||||
DRONE_FORMAT("drone_format"),
|
||||
|
||||
DEVICE_FORMAT("device_format"),
|
||||
|
||||
COVER_OPEN("cover_open"),
|
||||
|
||||
COVER_CLOSE("cover_close"),
|
||||
|
||||
PUTTER_OPEN("putter_open"),
|
||||
|
||||
PUTTER_CLOSE("putter_close"),
|
||||
|
||||
CHARGE_OPEN("charge_open"),
|
||||
|
||||
CHARGE_CLOSE("charge_close"),
|
||||
|
||||
FILE_UPLOAD_CALLBACK("file_upload_callback"),
|
||||
|
||||
FILE_UPLOAD_PROGRESS("fileupload_progress"),
|
||||
|
||||
OTA_PROGRESS("ota_progress"),
|
||||
|
||||
HIGHEST_PRIORITY_UPLOAD_FLIGHT_TASK_MEDIA("highest_priority_upload_flighttask_media"),
|
||||
|
||||
CONTROL_SOURCE_CHANGE("control_source_change"),
|
||||
|
||||
FLY_TO_POINT_PROGRESS("fly_to_point_progress"),
|
||||
|
||||
TAKE_OFF_TO_POINT_PROGRESS("takeoff_to_point_progress"),
|
||||
|
||||
DRC_STATUS_NOTIFY("drc_status_notify"),
|
||||
|
||||
JOYSTICK_INVALID_NOTIFY("joystick_invalid_notify"),
|
||||
|
||||
FLIGHT_AREAS_SYNC_PROGRESS("flight_areas_sync_progress"),
|
||||
|
||||
FLIGHT_AREAS_DRONE_LOCATION("flight_areas_drone_location"),
|
||||
|
||||
FLIGHT_AREAS_UPDATE("flight_areas_update"),
|
||||
|
||||
;
|
||||
|
||||
private String code;
|
||||
|
||||
BizCodeEnum(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.component.websocket.service;
|
||||
|
||||
import com.central.component.websocket.config.MyConcurrentWebSocketSession;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/25
|
||||
*/
|
||||
public interface IWebSocketManageService {
|
||||
|
||||
void put(String key, MyConcurrentWebSocketSession val);
|
||||
|
||||
void remove(String key, String sessionId);
|
||||
|
||||
Collection<MyConcurrentWebSocketSession> getValueWithWorkspace(String workspaceId);
|
||||
|
||||
Collection<MyConcurrentWebSocketSession> getValueWithWorkspaceAndUserType(String workspaceId, Integer userType);
|
||||
|
||||
Long getConnectedCount();
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.central.component.websocket.service;
|
||||
|
||||
import com.central.component.websocket.config.MyConcurrentWebSocketSession;
|
||||
import com.dji.sdk.websocket.WebSocketMessageResponse;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/24
|
||||
* @version 0.1
|
||||
*/
|
||||
public interface IWebSocketMessageService {
|
||||
|
||||
/**
|
||||
* Send a message to the specific connection.
|
||||
* @param session A WebSocket connection object
|
||||
* @param message message
|
||||
*/
|
||||
void sendMessage(MyConcurrentWebSocketSession session, WebSocketMessageResponse message);
|
||||
|
||||
/**
|
||||
* Send the same message to specific connection.
|
||||
* @param sessions A collection of WebSocket connection objects.
|
||||
* @param message message
|
||||
*/
|
||||
void sendBatch(Collection<MyConcurrentWebSocketSession> sessions, WebSocketMessageResponse message);
|
||||
|
||||
void sendBatch(String workspaceId, Integer userType, String bizCode, Object data);
|
||||
|
||||
void sendBatch(String workspaceId, String bizCode, Object data);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.central.component.websocket.service.impl;
|
||||
|
||||
import com.central.component.redis.RedisConst;
|
||||
import com.central.component.redis.RedisOpsUtils;
|
||||
import com.central.component.websocket.config.MyConcurrentWebSocketSession;
|
||||
import com.central.component.websocket.service.IWebSocketManageService;
|
||||
import com.central.manage.model.enums.UserTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.0
|
||||
* @date 2022/4/25
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class WebSocketManageServiceImpl implements IWebSocketManageService {
|
||||
|
||||
private static final ConcurrentHashMap<String, MyConcurrentWebSocketSession> SESSIONS = new ConcurrentHashMap<>(16);
|
||||
|
||||
@Override
|
||||
public void put(String key, MyConcurrentWebSocketSession val) {
|
||||
String[] name = key.split("/");
|
||||
if (name.length != 3) {
|
||||
log.debug("The key is out of format. [{workspaceId}/{userType}/{userId}]");
|
||||
return;
|
||||
}
|
||||
String sessionId = val.getId();
|
||||
String workspaceKey = RedisConst.WEBSOCKET_PREFIX + name[0];
|
||||
String userTypeKey = RedisConst.WEBSOCKET_PREFIX + UserTypeEnum.find(Integer.parseInt(name[1])).getDesc();
|
||||
RedisOpsUtils.hashSet(workspaceKey, sessionId, name[2]);
|
||||
RedisOpsUtils.hashSet(userTypeKey, sessionId, name[2]);
|
||||
SESSIONS.put(sessionId, val);
|
||||
RedisOpsUtils.expireKey(workspaceKey, RedisConst.WEBSOCKET_ALIVE_SECOND);
|
||||
RedisOpsUtils.expireKey(userTypeKey, RedisConst.WEBSOCKET_ALIVE_SECOND);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String key, String sessionId) {
|
||||
String[] name = key.split("/");
|
||||
if (name.length != 3) {
|
||||
log.debug("The key is out of format. [{workspaceId}/{userType}/{userId}]");
|
||||
return;
|
||||
}
|
||||
RedisOpsUtils.hashDel(RedisConst.WEBSOCKET_PREFIX + name[0], new String[] {sessionId});
|
||||
RedisOpsUtils.hashDel(RedisConst.WEBSOCKET_PREFIX + UserTypeEnum.find(Integer.parseInt(name[1])).getDesc(), new String[] {sessionId});
|
||||
SESSIONS.remove(sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<MyConcurrentWebSocketSession> getValueWithWorkspace(String workspaceId) {
|
||||
if (!StringUtils.hasText(workspaceId)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
String key = RedisConst.WEBSOCKET_PREFIX + workspaceId;
|
||||
|
||||
return RedisOpsUtils.hashKeys(key)
|
||||
.stream()
|
||||
.map(SESSIONS::get)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<MyConcurrentWebSocketSession> getValueWithWorkspaceAndUserType(String workspaceId, Integer userType) {
|
||||
String key = RedisConst.WEBSOCKET_PREFIX + UserTypeEnum.find(userType).getDesc();
|
||||
return RedisOpsUtils.hashKeys(key)
|
||||
.stream()
|
||||
.map(SESSIONS::get)
|
||||
.filter(getValueWithWorkspace(workspaceId)::contains)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getConnectedCount() {
|
||||
return SESSIONS.mappingCount();
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.central.component.websocket.service.impl;
|
||||
|
||||
import com.central.component.websocket.config.MyConcurrentWebSocketSession;
|
||||
import com.central.component.websocket.service.IWebSocketManageService;
|
||||
import com.central.component.websocket.service.IWebSocketMessageService;
|
||||
import com.dji.sdk.websocket.WebSocketMessageResponse;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/24
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class WebSocketMessageServiceImpl implements IWebSocketMessageService {
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Autowired
|
||||
private IWebSocketManageService webSocketManageService;
|
||||
|
||||
@Override
|
||||
public void sendMessage(MyConcurrentWebSocketSession session, WebSocketMessageResponse message) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!session.isOpen()) {
|
||||
session.close();
|
||||
log.debug("This session is closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
session.sendMessage(new TextMessage(mapper.writeValueAsBytes(message)));
|
||||
} catch (IOException e) {
|
||||
log.info("Failed to publish the message. {}", message.toString());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendBatch(Collection<MyConcurrentWebSocketSession> sessions, WebSocketMessageResponse message) {
|
||||
if (sessions.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
TextMessage data = new TextMessage(mapper.writeValueAsBytes(message));
|
||||
|
||||
for (MyConcurrentWebSocketSession session : sessions) {
|
||||
if (!session.isOpen()) {
|
||||
session.close();
|
||||
log.debug("This session is closed.");
|
||||
return;
|
||||
}
|
||||
session.sendMessage(data);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.info("Failed to publish the message. {}", message.toString());
|
||||
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendBatch(String workspaceId, Integer userType, String bizCode, Object data) {
|
||||
if (!StringUtils.hasText(workspaceId)) {
|
||||
throw new RuntimeException("Workspace ID does not exist.");
|
||||
}
|
||||
Collection<MyConcurrentWebSocketSession> sessions = Objects.isNull(userType) ?
|
||||
webSocketManageService.getValueWithWorkspace(workspaceId) :
|
||||
webSocketManageService.getValueWithWorkspaceAndUserType(workspaceId, userType);
|
||||
|
||||
this.sendBatch(sessions, new WebSocketMessageResponse()
|
||||
.setData(Objects.requireNonNullElse(data, ""))
|
||||
.setTimestamp(System.currentTimeMillis())
|
||||
.setBizCode(bizCode));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendBatch(String workspaceId, String bizCode, Object data) {
|
||||
this.sendBatch(workspaceId, null, bizCode, data);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.central.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/10
|
||||
* @version 0.1
|
||||
*/
|
||||
@Configuration
|
||||
public class GlobalThreadPoolConfiguration {
|
||||
|
||||
@Value("${thread.pool.core-pool-size: 10}")
|
||||
private int corePoolSize;
|
||||
|
||||
@Value("${thread.pool.maximum-pool-size: 20}")
|
||||
private int maximumPoolSize;
|
||||
|
||||
@Value("${thread.pool.keep-alive-time: 60}")
|
||||
private long keepAliveTime;
|
||||
|
||||
@Value("${thread.pool.queue.capacity: 1000}")
|
||||
private int capacity;
|
||||
|
||||
/**
|
||||
* A custom thread pool.
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public Executor threadPool() {
|
||||
return new ThreadPoolExecutor(corePoolSize,
|
||||
maximumPoolSize, keepAliveTime,
|
||||
TimeUnit.SECONDS, new LinkedBlockingQueue<>(capacity),
|
||||
Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.central.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Configuration
|
||||
public class SpringBeanConfiguration {
|
||||
|
||||
@Bean
|
||||
// @ConditionalOnMissingBean(ObjectMapper.class)
|
||||
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
|
||||
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
|
||||
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
|
||||
JavaTimeModule timeModule = new JavaTimeModule();
|
||||
timeModule.addDeserializer(LocalDateTime.class,
|
||||
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
timeModule.addSerializer(LocalDateTime.class,
|
||||
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
objectMapper.disable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS);
|
||||
objectMapper.registerModules(timeModule);
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
|
||||
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
|
||||
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
|
||||
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
|
||||
@Override
|
||||
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
gen.writeString("");
|
||||
}
|
||||
});
|
||||
return objectMapper;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.central.configuration.mvc;
|
||||
|
||||
import com.central.component.AuthInterceptor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class GlobalMVCConfigurer implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private AuthInterceptor authInterceptor;
|
||||
|
||||
private static List<String> excludePaths = new ArrayList<>();
|
||||
|
||||
@Value("${url.manage.prefix}")
|
||||
private String managePrefix;
|
||||
|
||||
@Value("${url.manage.version}")
|
||||
private String manageVersion;
|
||||
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// Exclude the login interface.
|
||||
excludePaths.add("/" + managePrefix + manageVersion + "/login");
|
||||
excludePaths.add("/" + managePrefix + manageVersion + "/token/refresh");
|
||||
excludePaths.add("/swagger-ui.html");
|
||||
excludePaths.add("/swagger-ui/**");
|
||||
excludePaths.add("/v3/**");
|
||||
excludePaths.add("/ui/**");
|
||||
// Intercept for all request interfaces.
|
||||
registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns(excludePaths);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.central.control.controller;
|
||||
|
||||
import com.central.control.model.enums.DroneAuthorityEnum;
|
||||
import com.central.control.model.enums.RemoteDebugMethodEnum;
|
||||
import com.central.cloud.api.control.model.param.*;
|
||||
import com.central.control.model.param.*;
|
||||
import com.central.control.service.IControlService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/7/29
|
||||
*/
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.control.prefix}${url.control.version}/devices")
|
||||
public class DockController {
|
||||
|
||||
@Autowired
|
||||
private IControlService controlService;
|
||||
|
||||
@PostMapping("/{sn}/jobs/{service_identifier}")
|
||||
public HttpResultResponse createControlJob(@PathVariable String sn,
|
||||
@PathVariable("service_identifier") String serviceIdentifier,
|
||||
@Valid @RequestBody(required = false) RemoteDebugParam param) {
|
||||
return controlService.controlDockDebug(sn, RemoteDebugMethodEnum.find(serviceIdentifier), param);
|
||||
}
|
||||
|
||||
@PostMapping("/{sn}/jobs/fly-to-point")
|
||||
public HttpResultResponse flyToPoint(@PathVariable String sn, @Valid @RequestBody FlyToPointParam param) {
|
||||
return controlService.flyToPoint(sn, param);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{sn}/jobs/fly-to-point")
|
||||
public HttpResultResponse flyToPointStop(@PathVariable String sn) {
|
||||
return controlService.flyToPointStop(sn);
|
||||
}
|
||||
|
||||
@PostMapping("/{sn}/jobs/takeoff-to-point")
|
||||
public HttpResultResponse takeoffToPoint(@PathVariable String sn, @Valid @RequestBody TakeoffToPointParam param) {
|
||||
return controlService.takeoffToPoint(sn, param);
|
||||
}
|
||||
|
||||
@PostMapping("/{sn}/authority/flight")
|
||||
public HttpResultResponse seizeFlightAuthority(@PathVariable String sn) {
|
||||
return controlService.seizeAuthority(sn, DroneAuthorityEnum.FLIGHT, null);
|
||||
}
|
||||
|
||||
@PostMapping("/{sn}/authority/payload")
|
||||
public HttpResultResponse seizePayloadAuthority(@PathVariable String sn, @Valid @RequestBody DronePayloadParam param) {
|
||||
return controlService.seizeAuthority(sn, DroneAuthorityEnum.PAYLOAD, param);
|
||||
}
|
||||
|
||||
@PostMapping("/{sn}/payload/commands")
|
||||
public HttpResultResponse payloadCommands(@PathVariable String sn, @Valid @RequestBody PayloadCommandsParam param) throws Exception {
|
||||
param.setSn(sn);
|
||||
return controlService.payloadCommands(param);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.central.control.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.control.model.dto.JwtAclDTO;
|
||||
import com.central.control.model.param.DrcConnectParam;
|
||||
import com.central.control.model.param.DrcModeParam;
|
||||
import com.central.control.service.IDrcService;
|
||||
import com.dji.sdk.cloudapi.control.DrcModeMqttBroker;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.control.prefix}${url.control.version}")
|
||||
public class DrcController {
|
||||
|
||||
@Autowired
|
||||
private IDrcService drcService;
|
||||
|
||||
@PostMapping("/workspaces/{workspace_id}/drc/connect")
|
||||
public HttpResultResponse drcConnect(@PathVariable("workspace_id") String workspaceId, HttpServletRequest request, @Valid @RequestBody DrcConnectParam param) {
|
||||
CustomClaim claims = (CustomClaim) request.getAttribute(TOKEN_CLAIM);
|
||||
|
||||
DrcModeMqttBroker brokerDTO = drcService.userDrcAuth(workspaceId, claims.getId(), claims.getUsername(), param);
|
||||
return HttpResultResponse.success(brokerDTO);
|
||||
}
|
||||
|
||||
@PostMapping("/workspaces/{workspace_id}/drc/enter")
|
||||
public HttpResultResponse drcEnter(@PathVariable("workspace_id") String workspaceId, @Valid @RequestBody DrcModeParam param) {
|
||||
JwtAclDTO acl = drcService.deviceDrcEnter(workspaceId, param);
|
||||
|
||||
return HttpResultResponse.success(acl);
|
||||
}
|
||||
|
||||
@PostMapping("/workspaces/{workspace_id}/drc/exit")
|
||||
public HttpResultResponse drcExit(@PathVariable("workspace_id") String workspaceId, @Valid @RequestBody DrcModeParam param) {
|
||||
drcService.deviceDrcExit(workspaceId, param);
|
||||
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.dji.sdk.cloudapi.device.AirConditionerStateEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/14
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AirConditionerMode extends RemoteDebugHandler {
|
||||
|
||||
private AirConditionerStateEnum action;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.dji.sdk.cloudapi.device.SwitchActionEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/25
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AlarmState extends RemoteDebugHandler {
|
||||
|
||||
private SwitchActionEnum action;
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.dji.sdk.cloudapi.device.BatteryStoreModeEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/14
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class BatteryStoreMode extends RemoteDebugHandler {
|
||||
|
||||
private BatteryStoreModeEnum action;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/12
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class JwtAclDTO {
|
||||
|
||||
private List<String> sub;
|
||||
|
||||
private List<String> pub;
|
||||
|
||||
private List<String> all;
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.dji.sdk.cloudapi.device.LinkWorkModeEnum;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/25
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class LinkWorkMode extends RemoteDebugHandler {
|
||||
|
||||
private LinkWorkModeEnum linkWorkMode;
|
||||
|
||||
@JsonCreator
|
||||
public LinkWorkMode(@JsonProperty("action") Integer linkWorkMode) {
|
||||
this.linkWorkMode = LinkWorkModeEnum.find(linkWorkMode);
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public Map toMap() {
|
||||
return Map.of("link_workmode", linkWorkMode.getMode());
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.common.util.SpringBeanUtilsTest;
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.cloudapi.device.DockModeCodeEnum;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/14
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class RemoteDebugOpenState extends RemoteDebugHandler {
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String sn) {
|
||||
IDeviceService deviceService = SpringBeanUtilsTest.getBean(IDeviceService.class);
|
||||
DockModeCodeEnum dockMode = deviceService.getDockMode(sn);
|
||||
return DockModeCodeEnum.IDLE == dockMode;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/1
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ResultNotifyDTO {
|
||||
|
||||
private Integer result;
|
||||
|
||||
private String message;
|
||||
|
||||
private String sn;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.common.util.SpringBeanUtilsTest;
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.dji.sdk.cloudapi.device.DroneModeCodeEnum;
|
||||
import com.dji.sdk.cloudapi.device.OsdDockDrone;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/19
|
||||
*/
|
||||
|
||||
public class ReturnHomeCancelState extends RemoteDebugHandler {
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String sn) {
|
||||
IDeviceRedisService deviceRedisService = SpringBeanUtilsTest.getBean(IDeviceRedisService.class);
|
||||
return deviceRedisService.getDeviceOnline(sn)
|
||||
.map(DeviceDTO::getChildDeviceSn)
|
||||
.flatMap(deviceSn -> deviceRedisService.getDeviceOsd(deviceSn, OsdDockDrone.class))
|
||||
.map(osd -> DroneModeCodeEnum.RETURN_AUTO == osd.getModeCode())
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.central.control.model.dto;
|
||||
|
||||
import com.central.common.util.SpringBeanUtilsTest;
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.dji.sdk.cloudapi.device.DroneModeCodeEnum;
|
||||
import com.dji.sdk.cloudapi.device.OsdDockDrone;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/19
|
||||
*/
|
||||
|
||||
public class ReturnHomeState extends RemoteDebugHandler {
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String sn) {
|
||||
IDeviceRedisService deviceRedisService = SpringBeanUtilsTest.getBean(IDeviceRedisService.class);
|
||||
return deviceRedisService.getDeviceOnline(sn)
|
||||
.map(DeviceDTO::getChildDeviceSn)
|
||||
.flatMap(deviceSn -> deviceRedisService.getDeviceOsd(deviceSn, OsdDockDrone.class))
|
||||
.map(osd -> osd.getElevation() > 0 && modeCodeCanReturnHome(osd.getModeCode()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private boolean modeCodeCanReturnHome(DroneModeCodeEnum modeCode) {
|
||||
return DroneModeCodeEnum.TAKEOFF_FINISHED == modeCode || DroneModeCodeEnum.TAKEOFF_AUTO == modeCode
|
||||
|| DroneModeCodeEnum.WAYLINE == modeCode || DroneModeCodeEnum.PANORAMIC_SHOT == modeCode
|
||||
|| DroneModeCodeEnum.ACTIVE_TRACK == modeCode || DroneModeCodeEnum.APAS == modeCode
|
||||
|| DroneModeCodeEnum.VIRTUAL_JOYSTICK == modeCode || DroneModeCodeEnum.MANUAL == modeCode;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/3
|
||||
*/
|
||||
public enum CameraModeEnum {
|
||||
|
||||
PHOTO, VIDEO;
|
||||
|
||||
@JsonValue
|
||||
public int getVal() {
|
||||
return ordinal();
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static CameraModeEnum find(int val) {
|
||||
return Arrays.stream(values()).filter(modeEnum -> modeEnum.ordinal() == val).findAny().get();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
@Getter
|
||||
public enum DrcMethodEnum {
|
||||
|
||||
DRC_MODE_ENTER("drc_mode_enter"),
|
||||
|
||||
DRC_MODE_EXIT("drc_mode_exit");
|
||||
|
||||
String method;
|
||||
|
||||
DrcMethodEnum(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/1
|
||||
*/
|
||||
public enum DroneAuthorityEnum {
|
||||
|
||||
FLIGHT(1), PAYLOAD(2);
|
||||
|
||||
int val;
|
||||
|
||||
DroneAuthorityEnum(int val) {
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public int getVal() {
|
||||
return val;
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/2/21
|
||||
*/
|
||||
@Getter
|
||||
public enum DroneControlMethodEnum {
|
||||
|
||||
FLIGHT_AUTHORITY_GRAB("flight_authority_grab"),
|
||||
|
||||
PAYLOAD_AUTHORITY_GRAB("payload_authority_grab"),
|
||||
|
||||
FLY_TO_POINT("fly_to_point"),
|
||||
|
||||
FLY_TO_POINT_STOP("fly_to_point_stop"),
|
||||
|
||||
TAKE_OFF_TO_POINT("takeoff_to_point");
|
||||
|
||||
String method;
|
||||
|
||||
DroneControlMethodEnum(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/13
|
||||
*/
|
||||
public enum GimbalResetModeEnum {
|
||||
|
||||
RECENTER, DOWN, RECENTER_PAN, PITCH_DOWN;
|
||||
|
||||
@JsonValue
|
||||
public int getVal() {
|
||||
return ordinal();
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static GimbalResetModeEnum find(int value) {
|
||||
return Arrays.stream(values()).filter(resetModeEnum -> resetModeEnum.ordinal() == value).findAny().get();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/13
|
||||
*/
|
||||
@Getter
|
||||
public enum MqttAclAccessEnum {
|
||||
|
||||
SUB(1),
|
||||
|
||||
PUB(2),
|
||||
|
||||
ALL(3);
|
||||
|
||||
int value;
|
||||
|
||||
MqttAclAccessEnum(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import com.central.cloud.api.control.service.impl.*;
|
||||
import com.central.control.service.impl.*;
|
||||
import com.dji.sdk.cloudapi.control.PayloadControlMethodEnum;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/2
|
||||
*/
|
||||
public enum PayloadCommandsEnum {
|
||||
|
||||
CAMERA_MODE_SWitCH(PayloadControlMethodEnum.CAMERA_MODE_SWITCH, CameraModeSwitchImpl.class),
|
||||
|
||||
CAMERA_PHOTO_TAKE(PayloadControlMethodEnum.CAMERA_PHOTO_TAKE, CameraPhotoTakeImpl.class),
|
||||
|
||||
CAMERA_RECORDING_START(PayloadControlMethodEnum.CAMERA_RECORDING_START, CameraRecordingStartImpl.class),
|
||||
|
||||
CAMERA_RECORDING_STOP(PayloadControlMethodEnum.CAMERA_RECORDING_STOP, CameraRecordingStopImpl.class),
|
||||
|
||||
CAMERA_AIM(PayloadControlMethodEnum.CAMERA_AIM, CameraAimImpl.class),
|
||||
|
||||
CAMERA_FOCAL_LENGTH_SET(PayloadControlMethodEnum.CAMERA_FOCAL_LENGTH_SET, CameraFocalLengthSetImpl.class),
|
||||
|
||||
GIMBAL_RESET(PayloadControlMethodEnum.GIMBAL_RESET, GimbalResetImpl.class);
|
||||
|
||||
PayloadControlMethodEnum cmd;
|
||||
|
||||
Class<? extends PayloadCommandsHandler> clazz;
|
||||
|
||||
PayloadCommandsEnum(PayloadControlMethodEnum cmd, Class<? extends PayloadCommandsHandler> clazz) {
|
||||
this.cmd = cmd;
|
||||
this.clazz = clazz;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getMethod() {
|
||||
return cmd.getPayloadMethod().getMethod();
|
||||
}
|
||||
|
||||
public Class<? extends PayloadCommandsHandler> getClazz() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public PayloadControlMethodEnum getCmd() {
|
||||
return cmd;
|
||||
}
|
||||
|
||||
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
|
||||
public static PayloadCommandsEnum find(String method) {
|
||||
return Arrays.stream(values()).filter(methodEnum -> methodEnum.cmd.getPayloadMethod().getMethod().equals(method)).findAny()
|
||||
.orElseThrow();
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package com.central.control.model.enums;
|
||||
|
||||
import com.central.cloud.api.control.model.dto.*;
|
||||
import com.central.control.model.dto.*;
|
||||
import com.central.control.service.impl.RemoteDebugHandler;
|
||||
import com.dji.sdk.cloudapi.debug.DebugMethodEnum;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/14
|
||||
*/
|
||||
@Getter
|
||||
public enum RemoteDebugMethodEnum {
|
||||
|
||||
DEBUG_MODE_OPEN(DebugMethodEnum.DEBUG_MODE_OPEN, false, RemoteDebugOpenState.class),
|
||||
|
||||
DEBUG_MODE_CLOSE(DebugMethodEnum.DEBUG_MODE_CLOSE, false, null),
|
||||
|
||||
SUPPLEMENT_LIGHT_OPEN(DebugMethodEnum.SUPPLEMENT_LIGHT_OPEN, false, null),
|
||||
|
||||
SUPPLEMENT_LIGHT_CLOSE(DebugMethodEnum.SUPPLEMENT_LIGHT_CLOSE, false, null),
|
||||
|
||||
RETURN_HOME("return_home", false, ReturnHomeState.class),
|
||||
|
||||
RETURN_HOME_CANCEL("return_home_cancel", false, ReturnHomeCancelState.class),
|
||||
|
||||
DEVICE_REBOOT(DebugMethodEnum.DEVICE_REBOOT, true, null),
|
||||
|
||||
DRONE_OPEN(DebugMethodEnum.DRONE_OPEN, true, null),
|
||||
|
||||
DRONE_CLOSE(DebugMethodEnum.DRONE_CLOSE, true, null),
|
||||
|
||||
DRONE_FORMAT(DebugMethodEnum.DRONE_FORMAT, true, null),
|
||||
|
||||
DEVICE_FORMAT(DebugMethodEnum.DEVICE_FORMAT, true, null),
|
||||
|
||||
COVER_OPEN(DebugMethodEnum.COVER_OPEN, true, null),
|
||||
|
||||
COVER_CLOSE(DebugMethodEnum.COVER_CLOSE, true, null),
|
||||
|
||||
PUTTER_OPEN(DebugMethodEnum.PUTTER_OPEN, true, null),
|
||||
|
||||
PUTTER_CLOSE(DebugMethodEnum.PUTTER_CLOSE, true, null),
|
||||
|
||||
CHARGE_OPEN(DebugMethodEnum.CHARGE_OPEN, true, null),
|
||||
|
||||
CHARGE_CLOSE(DebugMethodEnum.CHARGE_CLOSE, true, null),
|
||||
|
||||
BATTERY_MAINTENANCE_SWITCH(DebugMethodEnum.BATTERY_MAINTENANCE_SWITCH, false, AlarmState.class),
|
||||
|
||||
ALARM_STATE_SWITCH(DebugMethodEnum.ALARM_STATE_SWITCH, false, AlarmState.class),
|
||||
|
||||
BATTERY_STORE_MODE_SWITCH(DebugMethodEnum.BATTERY_STORE_MODE_SWITCH, false, BatteryStoreMode.class),
|
||||
|
||||
SDR_WORK_MODE_SWITCH(DebugMethodEnum.SDR_WORKMODE_SWITCH, false, LinkWorkMode.class),
|
||||
|
||||
AIR_CONDITIONER_MODE_SWITCH(DebugMethodEnum.AIR_CONDITIONER_MODE_SWITCH, false, AirConditionerMode.class);
|
||||
|
||||
private DebugMethodEnum debugMethodEnum;
|
||||
|
||||
private String method;
|
||||
|
||||
private boolean progress;
|
||||
|
||||
private Class<? extends RemoteDebugHandler> clazz;
|
||||
|
||||
RemoteDebugMethodEnum(DebugMethodEnum debugMethodEnum, boolean progress, Class<? extends RemoteDebugHandler> clazz) {
|
||||
this.debugMethodEnum = debugMethodEnum;
|
||||
this.progress = progress;
|
||||
this.clazz = clazz;
|
||||
this.method = debugMethodEnum.getMethod();
|
||||
}
|
||||
|
||||
RemoteDebugMethodEnum(String method, boolean progress, Class<? extends RemoteDebugHandler> clazz) {
|
||||
this.debugMethodEnum = null;
|
||||
this.progress = progress;
|
||||
this.clazz = clazz;
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static RemoteDebugMethodEnum find(String method) {
|
||||
return Arrays.stream(values())
|
||||
.filter(methodEnum -> methodEnum.method.equals(method)
|
||||
|| (Objects.nonNull(methodEnum.debugMethodEnum)
|
||||
&& methodEnum.debugMethodEnum.getMethod().equals(method)))
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/2/2
|
||||
*/
|
||||
@Data
|
||||
public class DeviceDrcInfoParam {
|
||||
|
||||
@Range(min = 1, max = 30)
|
||||
private Integer osdFrequency = 10;
|
||||
|
||||
@Range(min = 1, max = 30)
|
||||
private Integer hsiFrequency = 1;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.central.component.redis.RedisConst;
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
@Data
|
||||
public class DrcConnectParam {
|
||||
|
||||
private String clientId;
|
||||
|
||||
@Range(min = 1800, max = 86400)
|
||||
private long expireSec = RedisConst.DRC_MODE_ALIVE_SECOND;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.central.component.redis.RedisConst;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DrcModeParam {
|
||||
|
||||
@NotBlank
|
||||
private String clientId;
|
||||
|
||||
@NotBlank
|
||||
private String dockSn;
|
||||
|
||||
@Range(min = 1800, max = 86400)
|
||||
@Builder.Default
|
||||
private long expireSec = RedisConst.DRC_MODE_ALIVE_SECOND;
|
||||
|
||||
@Valid
|
||||
@Builder.Default
|
||||
private DeviceDrcInfoParam deviceInfo = new DeviceDrcInfoParam();
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.dji.sdk.cloudapi.control.CameraTypeEnum;
|
||||
import com.dji.sdk.cloudapi.control.GimbalResetModeEnum;
|
||||
import com.dji.sdk.cloudapi.device.CameraModeEnum;
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/1
|
||||
*/
|
||||
@Data
|
||||
public class DronePayloadParam {
|
||||
|
||||
@Pattern(regexp = "\\d+-\\d+-\\d+")
|
||||
@NotNull
|
||||
private String payloadIndex;
|
||||
|
||||
private CameraTypeEnum cameraType;
|
||||
|
||||
@Range(min = 2, max = 200)
|
||||
private Float zoomFactor;
|
||||
|
||||
private CameraModeEnum cameraMode;
|
||||
|
||||
/**
|
||||
* true: Lock the gimbal, the gimbal and the drone rotate together.
|
||||
* false: Only the gimbal rotates, but the drone does not.
|
||||
*/
|
||||
private Boolean locked;
|
||||
|
||||
private Double pitchSpeed;
|
||||
|
||||
/**
|
||||
* Only valid when locked is false.
|
||||
*/
|
||||
private Double yawSpeed;
|
||||
|
||||
/**
|
||||
* upper left corner as center point
|
||||
*/
|
||||
@Range(min = 0, max = 1)
|
||||
private Double x;
|
||||
|
||||
@Range(min = 0, max = 1)
|
||||
private Double y;
|
||||
|
||||
private GimbalResetModeEnum resetMode;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.dji.sdk.cloudapi.control.Point;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/2/14
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class FlyToPointParam {
|
||||
|
||||
private String flyToId;
|
||||
|
||||
@Range(min = 1, max = 15)
|
||||
@NotNull
|
||||
private Integer maxSpeed;
|
||||
|
||||
/**
|
||||
* The M30 series only support one point.
|
||||
*/
|
||||
@Size(min = 1)
|
||||
@NotNull
|
||||
private List<@Valid Point> points;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.central.control.model.enums.PayloadCommandsEnum;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/2
|
||||
*/
|
||||
@Data
|
||||
public class PayloadCommandsParam {
|
||||
|
||||
private String sn;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
private PayloadCommandsEnum cmd;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
private DronePayloadParam data;
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/11/14
|
||||
*/
|
||||
@Data
|
||||
public class RemoteDebugParam {
|
||||
|
||||
@NotNull
|
||||
private Integer action;
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.central.control.model.param;
|
||||
|
||||
import com.dji.sdk.cloudapi.control.CommanderFlightModeEnum;
|
||||
import com.dji.sdk.cloudapi.control.CommanderModeLostActionEnum;
|
||||
import com.dji.sdk.cloudapi.device.ExitWaylineWhenRcLostEnum;
|
||||
import com.dji.sdk.cloudapi.device.RcLostActionEnum;
|
||||
import com.dji.sdk.cloudapi.wayline.RthModeEnum;
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Range;
|
||||
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/3/1
|
||||
*/
|
||||
@Data
|
||||
public class TakeoffToPointParam {
|
||||
|
||||
private String flightId;
|
||||
|
||||
@Range(min = -180, max = 180)
|
||||
@NotNull
|
||||
private Double targetLongitude;
|
||||
|
||||
@Range(min = -90, max = 90)
|
||||
@NotNull
|
||||
private Double targetLatitude;
|
||||
|
||||
@Range(min = 2, max = 10000)
|
||||
@NotNull
|
||||
private Double targetHeight;
|
||||
|
||||
@Range(min = 2, max = 1500)
|
||||
@NotNull
|
||||
private Double securityTakeoffHeight;
|
||||
|
||||
@Range(min = 2, max = 1500)
|
||||
@NotNull
|
||||
private Double rthAltitude;
|
||||
|
||||
@NotNull
|
||||
private RcLostActionEnum rcLostAction;
|
||||
|
||||
@NotNull
|
||||
private ExitWaylineWhenRcLostEnum exitWaylineWhenRcLost;
|
||||
|
||||
@Range(min = 1, max = 15)
|
||||
@NotNull
|
||||
private Double maxSpeed;
|
||||
|
||||
private RthModeEnum rthMode;
|
||||
|
||||
private CommanderModeLostActionEnum commanderModeLostAction;
|
||||
|
||||
private CommanderFlightModeEnum commanderFlightMode;
|
||||
|
||||
@Min(2)
|
||||
@Max(3000)
|
||||
private Float commanderFlightHeight;
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.central.control.service;
|
||||
|
||||
import com.central.control.model.enums.DroneAuthorityEnum;
|
||||
import com.central.control.model.enums.RemoteDebugMethodEnum;
|
||||
import com.central.cloud.api.control.model.param.*;
|
||||
import com.central.control.model.param.*;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/7/29
|
||||
*/
|
||||
public interface IControlService {
|
||||
|
||||
/**
|
||||
* Remotely debug the dock via commands.
|
||||
* @param sn
|
||||
* @param serviceIdentifier
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse controlDockDebug(String sn, RemoteDebugMethodEnum serviceIdentifier, RemoteDebugParam param);
|
||||
|
||||
/**
|
||||
* Make the drone fly to the target point.
|
||||
* @param sn
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse flyToPoint(String sn, FlyToPointParam param);
|
||||
|
||||
/**
|
||||
* End the mission of flying the drone to the target point.
|
||||
* @param sn
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse flyToPointStop(String sn);
|
||||
|
||||
/**
|
||||
* Handle progress result notifications for fly to target point.
|
||||
* @param receiver
|
||||
* @param headers
|
||||
* @return
|
||||
*/
|
||||
// CommonTopicReceiver handleFlyToPointProgress(CommonTopicReceiver receiver, MessageHeaders headers);
|
||||
|
||||
/**
|
||||
* Control the drone to take off.
|
||||
* @param sn
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse takeoffToPoint(String sn, TakeoffToPointParam param);
|
||||
|
||||
/**
|
||||
* Seize the control authority of the drone or the payload control authority.
|
||||
* @param sn
|
||||
* @param authority
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse seizeAuthority(String sn, DroneAuthorityEnum authority, DronePayloadParam param);
|
||||
|
||||
/**
|
||||
* Control the payload of the drone.
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
HttpResultResponse payloadCommands(PayloadCommandsParam param) throws Exception;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.central.control.service;
|
||||
|
||||
import com.central.control.model.dto.JwtAclDTO;
|
||||
import com.central.control.model.param.DrcConnectParam;
|
||||
import com.central.control.model.param.DrcModeParam;
|
||||
import com.dji.sdk.cloudapi.control.DrcModeMqttBroker;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
public interface IDrcService {
|
||||
|
||||
/**
|
||||
* Save the drc mode of dock in redis.
|
||||
* @param dockSn
|
||||
* @param clientId
|
||||
*/
|
||||
void setDrcModeInRedis(String dockSn, String clientId);
|
||||
|
||||
/**
|
||||
* Query the client that is controlling the dock.
|
||||
* @param dockSn
|
||||
* @return clientId
|
||||
*/
|
||||
String getDrcModeInRedis(String dockSn);
|
||||
|
||||
/**
|
||||
* Delete the drc mode of dock in redis.
|
||||
* @param dockSn
|
||||
* @return
|
||||
*/
|
||||
Boolean delDrcModeInRedis(String dockSn);
|
||||
|
||||
/**
|
||||
* Provide mqtt options for the control terminal.
|
||||
* @param workspaceId
|
||||
* @param userId
|
||||
* @param username
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
DrcModeMqttBroker userDrcAuth(String workspaceId, String userId, String username, DrcConnectParam param);
|
||||
|
||||
/**
|
||||
* Make the dock enter drc mode. And grant relevant permissions.
|
||||
* @param workspaceId
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
JwtAclDTO deviceDrcEnter(String workspaceId, DrcModeParam param);
|
||||
|
||||
/**
|
||||
* Make the dock exit drc mode.
|
||||
* @param workspaceId
|
||||
* @param param
|
||||
*/
|
||||
void deviceDrcExit(String workspaceId, DrcModeParam param);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraAimImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraAimImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean valid() {
|
||||
return Objects.nonNull(param.getX()) && Objects.nonNull(param.getY())
|
||||
&& Objects.nonNull(param.getLocked()) && Objects.nonNull(param.getCameraType());
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.dji.sdk.cloudapi.control.CameraTypeEnum;
|
||||
import com.dji.sdk.cloudapi.device.CameraStateEnum;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraFocalLengthSetImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraFocalLengthSetImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean valid() {
|
||||
return Objects.nonNull(param.getCameraType()) && Objects.nonNull(param.getZoomFactor())
|
||||
&& (CameraTypeEnum.ZOOM == param.getCameraType()
|
||||
|| CameraTypeEnum.IR == param.getCameraType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String deviceSn) {
|
||||
super.canPublish(deviceSn);
|
||||
if (CameraStateEnum.WORKING == osdCamera.getPhotoState()) {
|
||||
return false;
|
||||
}
|
||||
switch (param.getCameraType()) {
|
||||
case IR:
|
||||
return Objects.nonNull(osdCamera.getIrZoomFactor())
|
||||
&& param.getZoomFactor().intValue() != osdCamera.getIrZoomFactor();
|
||||
case ZOOM:
|
||||
return param.getZoomFactor().intValue() != osdCamera.getZoomFactor();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.dji.sdk.cloudapi.device.CameraStateEnum;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraModeSwitchImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraModeSwitchImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean valid() {
|
||||
return Objects.nonNull(param.getCameraMode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String deviceSn) {
|
||||
super.canPublish(deviceSn);
|
||||
return param.getCameraMode() != osdCamera.getCameraMode()
|
||||
&& CameraStateEnum.IDLE == osdCamera.getPhotoState()
|
||||
&& CameraStateEnum.IDLE == osdCamera.getRecordingState();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.dji.sdk.cloudapi.device.CameraStateEnum;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraPhotoTakeImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraPhotoTakeImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String deviceSn) {
|
||||
super.canPublish(deviceSn);
|
||||
return CameraStateEnum.WORKING != osdCamera.getPhotoState() && osdCamera.getRemainPhotoNum() > 0;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.dji.sdk.cloudapi.device.CameraModeEnum;
|
||||
import com.dji.sdk.cloudapi.device.CameraStateEnum;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraRecordingStartImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraRecordingStartImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String deviceSn) {
|
||||
super.canPublish(deviceSn);
|
||||
return CameraModeEnum.VIDEO == osdCamera.getCameraMode()
|
||||
&& CameraStateEnum.IDLE == osdCamera.getRecordingState()
|
||||
&& osdCamera.getRemainRecordDuration() > 0;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.dji.sdk.cloudapi.device.CameraStateEnum;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class CameraRecordingStopImpl extends PayloadCommandsHandler {
|
||||
|
||||
public CameraRecordingStopImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPublish(String deviceSn) {
|
||||
super.canPublish(deviceSn);
|
||||
return CameraStateEnum.WORKING == osdCamera.getRecordingState();
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.component.websocket.service.IWebSocketMessageService;
|
||||
import com.central.control.model.enums.DroneAuthorityEnum;
|
||||
import com.central.control.model.enums.RemoteDebugMethodEnum;
|
||||
import com.central.cloud.api.control.model.param.*;
|
||||
import com.central.control.model.param.*;
|
||||
import com.central.control.service.IControlService;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDevicePayloadService;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.cloudapi.control.FlyToPointRequest;
|
||||
import com.dji.sdk.cloudapi.control.PayloadAuthorityGrabRequest;
|
||||
import com.dji.sdk.cloudapi.control.TakeoffToPointRequest;
|
||||
import com.dji.sdk.cloudapi.control.api.AbstractControlService;
|
||||
import com.dji.sdk.cloudapi.debug.DebugMethodEnum;
|
||||
import com.dji.sdk.cloudapi.debug.api.AbstractDebugService;
|
||||
import com.dji.sdk.cloudapi.device.DockModeCodeEnum;
|
||||
import com.dji.sdk.cloudapi.device.DroneModeCodeEnum;
|
||||
import com.dji.sdk.cloudapi.device.PayloadIndex;
|
||||
import com.dji.sdk.cloudapi.wayline.api.AbstractWaylineService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.SDKManager;
|
||||
import com.dji.sdk.exception.CloudSDKErrorEnum;
|
||||
import com.dji.sdk.mqtt.services.ServicesReplyData;
|
||||
import com.dji.sdk.mqtt.services.TopicServicesResponse;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/7/29
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ControlServiceImpl implements IControlService {
|
||||
|
||||
@Autowired
|
||||
private IWebSocketMessageService webSocketMessageService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceService deviceService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceRedisService deviceRedisService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Autowired
|
||||
private IDevicePayloadService devicePayloadService;
|
||||
|
||||
@Autowired
|
||||
private AbstractControlService abstractControlService;
|
||||
|
||||
@Autowired
|
||||
private AbstractDebugService abstractDebugService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("SDKWaylineService")
|
||||
private AbstractWaylineService abstractWaylineService;
|
||||
|
||||
private RemoteDebugHandler checkDebugCondition(String sn, RemoteDebugParam param, RemoteDebugMethodEnum controlMethodEnum) {
|
||||
RemoteDebugHandler handler = Objects.nonNull(controlMethodEnum.getClazz()) ?
|
||||
mapper.convertValue(Objects.nonNull(param) ? param : new Object(), controlMethodEnum.getClazz())
|
||||
: new RemoteDebugHandler();
|
||||
if (!handler.canPublish(sn)) {
|
||||
throw new RuntimeException("The current state of the dock does not support this function.");
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse controlDockDebug(String sn, RemoteDebugMethodEnum controlMethodEnum, RemoteDebugParam param) {
|
||||
DebugMethodEnum methodEnum = controlMethodEnum.getDebugMethodEnum();
|
||||
RemoteDebugHandler data = checkDebugCondition(sn, param, controlMethodEnum);
|
||||
|
||||
boolean isExist = deviceRedisService.checkDeviceOnline(sn);
|
||||
if (!isExist) {
|
||||
return HttpResultResponse.error("The dock is offline.");
|
||||
}
|
||||
TopicServicesResponse response;
|
||||
switch (controlMethodEnum) {
|
||||
case RETURN_HOME:
|
||||
response = abstractWaylineService.returnHome(SDKManager.getDeviceSDK(sn));
|
||||
break;
|
||||
case RETURN_HOME_CANCEL:
|
||||
response = abstractWaylineService.returnHomeCancel(SDKManager.getDeviceSDK(sn));
|
||||
break;
|
||||
default:
|
||||
response = abstractDebugService.remoteDebug(SDKManager.getDeviceSDK(sn), methodEnum,
|
||||
Objects.nonNull(methodEnum.getClazz()) ? mapper.convertValue(data, methodEnum.getClazz()) : null);
|
||||
}
|
||||
ServicesReplyData serviceReply = (ServicesReplyData) response.getData();
|
||||
if (!serviceReply.getResult().isSuccess()) {
|
||||
return HttpResultResponse.error(serviceReply.getResult());
|
||||
}
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
private void checkFlyToCondition(String dockSn) {
|
||||
// TODO 设备固件版本不兼容情况
|
||||
Optional<DeviceDTO> dockOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (dockOpt.isEmpty()) {
|
||||
throw new RuntimeException("The dock is offline, please restart the dock.");
|
||||
}
|
||||
|
||||
DroneModeCodeEnum deviceMode = deviceService.getDeviceMode(dockOpt.get().getChildDeviceSn());
|
||||
if (DroneModeCodeEnum.MANUAL != deviceMode) {
|
||||
throw new RuntimeException("The current state of the drone does not support this function, please try again later.");
|
||||
}
|
||||
|
||||
HttpResultResponse result = seizeAuthority(dockSn, DroneAuthorityEnum.FLIGHT, null);
|
||||
if (HttpResultResponse.CODE_SUCCESS != result.getCode()) {
|
||||
throw new IllegalArgumentException(result.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse flyToPoint(String sn, FlyToPointParam param) {
|
||||
checkFlyToCondition(sn);
|
||||
|
||||
param.setFlyToId(UUID.randomUUID().toString());
|
||||
TopicServicesResponse<ServicesReplyData> response = abstractControlService.flyToPoint(
|
||||
SDKManager.getDeviceSDK(sn), mapper.convertValue(param, FlyToPointRequest.class));
|
||||
ServicesReplyData reply = response.getData();
|
||||
return reply.getResult().isSuccess() ?
|
||||
HttpResultResponse.success()
|
||||
: HttpResultResponse.error("Flying to the target point failed. " + reply.getResult());
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse flyToPointStop(String sn) {
|
||||
TopicServicesResponse<ServicesReplyData> response = abstractControlService.flyToPointStop(SDKManager.getDeviceSDK(sn));
|
||||
ServicesReplyData reply = response.getData();
|
||||
|
||||
return reply.getResult().isSuccess() ?
|
||||
HttpResultResponse.success()
|
||||
: HttpResultResponse.error("The drone flying to the target point failed to stop. " + reply.getResult());
|
||||
}
|
||||
|
||||
private void checkTakeoffCondition(String dockSn) {
|
||||
Optional<DeviceDTO> dockOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (dockOpt.isEmpty() || DockModeCodeEnum.IDLE != deviceService.getDockMode(dockSn)) {
|
||||
throw new RuntimeException("The current state does not support takeoff.");
|
||||
}
|
||||
|
||||
HttpResultResponse result = seizeAuthority(dockSn, DroneAuthorityEnum.FLIGHT, null);
|
||||
if (HttpResultResponse.CODE_SUCCESS != result.getCode()) {
|
||||
throw new IllegalArgumentException(result.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse takeoffToPoint(String sn, TakeoffToPointParam param) {
|
||||
checkTakeoffCondition(sn);
|
||||
|
||||
param.setFlightId(UUID.randomUUID().toString());
|
||||
TopicServicesResponse<ServicesReplyData> response = abstractControlService.takeoffToPoint(
|
||||
SDKManager.getDeviceSDK(sn), mapper.convertValue(param, TakeoffToPointRequest.class));
|
||||
ServicesReplyData reply = response.getData();
|
||||
return reply.getResult().isSuccess() ?
|
||||
HttpResultResponse.success()
|
||||
: HttpResultResponse.error("The drone failed to take off. " + reply.getResult());
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse seizeAuthority(String sn, DroneAuthorityEnum authority, DronePayloadParam param) {
|
||||
TopicServicesResponse<ServicesReplyData> response;
|
||||
switch (authority) {
|
||||
case FLIGHT:
|
||||
if (deviceService.checkAuthorityFlight(sn)) {
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
response = abstractControlService.flightAuthorityGrab(SDKManager.getDeviceSDK(sn));
|
||||
break;
|
||||
case PAYLOAD:
|
||||
if (checkPayloadAuthority(sn, param.getPayloadIndex())) {
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
response = abstractControlService.payloadAuthorityGrab(SDKManager.getDeviceSDK(sn),
|
||||
new PayloadAuthorityGrabRequest().setPayloadIndex(new PayloadIndex(param.getPayloadIndex())));
|
||||
break;
|
||||
default:
|
||||
return HttpResultResponse.error(CloudSDKErrorEnum.INVALID_PARAMETER);
|
||||
}
|
||||
|
||||
ServicesReplyData serviceReply = response.getData();
|
||||
return serviceReply.getResult().isSuccess() ?
|
||||
HttpResultResponse.success()
|
||||
: HttpResultResponse.error(serviceReply.getResult());
|
||||
}
|
||||
|
||||
private Boolean checkPayloadAuthority(String sn, String payloadIndex) {
|
||||
Optional<DeviceDTO> dockOpt = deviceRedisService.getDeviceOnline(sn);
|
||||
if (dockOpt.isEmpty()) {
|
||||
throw new RuntimeException("The dock is offline, please restart the dock.");
|
||||
}
|
||||
return devicePayloadService.checkAuthorityPayload(dockOpt.get().getChildDeviceSn(), payloadIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResultResponse payloadCommands(PayloadCommandsParam param) throws Exception {
|
||||
param.getCmd().getClazz()
|
||||
.getDeclaredConstructor(DronePayloadParam.class)
|
||||
.newInstance(param.getData())
|
||||
.checkCondition(param.getSn());
|
||||
|
||||
TopicServicesResponse<ServicesReplyData> response = abstractControlService.payloadControl(
|
||||
SDKManager.getDeviceSDK(param.getSn()), param.getCmd().getCmd(),
|
||||
mapper.convertValue(param.getData(), param.getCmd().getCmd().getClazz()));
|
||||
|
||||
ServicesReplyData serviceReply = response.getData();
|
||||
return serviceReply.getResult().isSuccess() ?
|
||||
HttpResultResponse.success()
|
||||
: HttpResultResponse.error(serviceReply.getResult());
|
||||
}
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.component.mqtt.config.MqttPropertyConfiguration;
|
||||
import com.central.component.mqtt.model.EventsReceiver;
|
||||
import com.central.component.mqtt.model.MapKeyConst;
|
||||
import com.central.component.redis.RedisConst;
|
||||
import com.central.component.redis.RedisOpsUtils;
|
||||
import com.central.component.websocket.service.IWebSocketMessageService;
|
||||
import com.central.control.model.dto.JwtAclDTO;
|
||||
import com.central.control.model.enums.DroneAuthorityEnum;
|
||||
import com.central.control.model.enums.MqttAclAccessEnum;
|
||||
import com.central.control.model.param.DrcConnectParam;
|
||||
import com.central.control.model.param.DrcModeParam;
|
||||
import com.central.control.service.IControlService;
|
||||
import com.central.control.service.IDrcService;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.central.wayline.model.enums.WaylineJobStatusEnum;
|
||||
import com.central.wayline.model.enums.WaylineTaskStatusEnum;
|
||||
import com.central.wayline.model.param.UpdateJobParam;
|
||||
import com.central.wayline.service.IFlightTaskService;
|
||||
import com.central.wayline.service.IWaylineJobService;
|
||||
import com.central.wayline.service.IWaylineRedisService;
|
||||
import com.dji.sdk.cloudapi.control.DrcModeEnterRequest;
|
||||
import com.dji.sdk.cloudapi.control.DrcModeMqttBroker;
|
||||
import com.dji.sdk.cloudapi.control.api.AbstractControlService;
|
||||
import com.dji.sdk.cloudapi.device.DockModeCodeEnum;
|
||||
import com.dji.sdk.cloudapi.device.OsdDockDrone;
|
||||
import com.dji.sdk.cloudapi.wayline.FlighttaskProgress;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.SDKManager;
|
||||
import com.dji.sdk.mqtt.TopicConst;
|
||||
import com.dji.sdk.mqtt.services.ServicesReplyData;
|
||||
import com.dji.sdk.mqtt.services.TopicServicesResponse;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2023/1/11
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class DrcServiceImpl implements IDrcService {
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private IWaylineJobService waylineJobService;
|
||||
|
||||
@Autowired
|
||||
private IFlightTaskService flighttaskService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceService deviceService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Autowired
|
||||
private IWebSocketMessageService webSocketMessageService;
|
||||
|
||||
@Autowired
|
||||
private IControlService controlService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceRedisService deviceRedisService;
|
||||
|
||||
@Autowired
|
||||
private IWaylineRedisService waylineRedisService;
|
||||
|
||||
@Autowired
|
||||
private AbstractControlService abstractControlService;
|
||||
|
||||
@Override
|
||||
public void setDrcModeInRedis(String dockSn, String clientId) {
|
||||
RedisOpsUtils.setWithExpire(RedisConst.DRC_PREFIX + dockSn, clientId, RedisConst.DRC_MODE_ALIVE_SECOND);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDrcModeInRedis(String dockSn) {
|
||||
return (String) RedisOpsUtils.get(RedisConst.DRC_PREFIX + dockSn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean delDrcModeInRedis(String dockSn) {
|
||||
return RedisOpsUtils.del(RedisConst.DRC_PREFIX + dockSn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DrcModeMqttBroker userDrcAuth(String workspaceId, String userId, String username, DrcConnectParam param) {
|
||||
|
||||
// refresh token
|
||||
String clientId = param.getClientId();
|
||||
// first time
|
||||
if (!StringUtils.hasText(clientId) || !RedisOpsUtils.checkExist(RedisConst.MQTT_ACL_PREFIX + clientId)) {
|
||||
clientId = userId + "-" + System.currentTimeMillis();
|
||||
RedisOpsUtils.hashSet(RedisConst.MQTT_ACL_PREFIX + clientId, "", MqttAclAccessEnum.ALL.getValue());
|
||||
}
|
||||
|
||||
String key = RedisConst.MQTT_ACL_PREFIX + clientId;
|
||||
|
||||
try {
|
||||
RedisOpsUtils.expireKey(key, RedisConst.DRC_MODE_ALIVE_SECOND);
|
||||
|
||||
return MqttPropertyConfiguration.getMqttBrokerWithDrc(
|
||||
clientId, username, param.getExpireSec(), Collections.emptyMap());
|
||||
} catch (RuntimeException e) {
|
||||
RedisOpsUtils.del(key);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void checkDrcModeCondition(String workspaceId, String dockSn) {
|
||||
Optional<EventsReceiver<FlighttaskProgress>> runningOpt = waylineRedisService.getRunningWaylineJob(dockSn);
|
||||
if (runningOpt.isPresent() && WaylineJobStatusEnum.IN_PROGRESS == waylineJobService.getWaylineState(dockSn)) {
|
||||
flighttaskService.updateJobStatus(workspaceId, runningOpt.get().getBid(),
|
||||
UpdateJobParam.builder().status(WaylineTaskStatusEnum.PAUSE).build());
|
||||
}
|
||||
|
||||
DockModeCodeEnum dockMode = deviceService.getDockMode(dockSn);
|
||||
Optional<DeviceDTO> dockOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (dockOpt.isPresent() && (DockModeCodeEnum.IDLE == dockMode || DockModeCodeEnum.WORKING == dockMode)) {
|
||||
Optional<OsdDockDrone> deviceOsd = deviceRedisService.getDeviceOsd(dockOpt.get().getChildDeviceSn(), OsdDockDrone.class);
|
||||
if (deviceOsd.isEmpty() || deviceOsd.get().getElevation() <= 0) {
|
||||
throw new RuntimeException("The drone is not in the sky and cannot enter command flight mode.");
|
||||
}
|
||||
} else {
|
||||
throw new RuntimeException("The current state of the dock does not support entering command flight mode.");
|
||||
}
|
||||
|
||||
HttpResultResponse result = controlService.seizeAuthority(dockSn, DroneAuthorityEnum.FLIGHT, null);
|
||||
if (HttpResultResponse.CODE_SUCCESS != result.getCode()) {
|
||||
throw new IllegalArgumentException(result.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public JwtAclDTO deviceDrcEnter(String workspaceId, DrcModeParam param) {
|
||||
String topic = TopicConst.THING_MODEL_PRE + TopicConst.PRODUCT + param.getDockSn() + TopicConst.DRC;
|
||||
String pubTopic = topic + TopicConst.DOWN;
|
||||
String subTopic = topic + TopicConst.UP;
|
||||
|
||||
// If the dock is in drc mode, refresh the permissions directly.
|
||||
if (deviceService.checkDockDrcMode(param.getDockSn())
|
||||
&& param.getClientId().equals(this.getDrcModeInRedis(param.getDockSn()))) {
|
||||
refreshAcl(param.getDockSn(), param.getClientId(), topic, subTopic);
|
||||
return JwtAclDTO.builder().sub(List.of(subTopic)).pub(List.of(pubTopic)).build();
|
||||
}
|
||||
|
||||
checkDrcModeCondition(workspaceId, param.getDockSn());
|
||||
|
||||
TopicServicesResponse<ServicesReplyData> reply = abstractControlService.drcModeEnter(
|
||||
SDKManager.getDeviceSDK(param.getDockSn()),
|
||||
new DrcModeEnterRequest()
|
||||
.setMqttBroker(MqttPropertyConfiguration.getMqttBrokerWithDrc(param.getDockSn() + "-" + System.currentTimeMillis(), param.getDockSn(),
|
||||
RedisConst.DRC_MODE_ALIVE_SECOND.longValue(),
|
||||
Map.of(MapKeyConst.ACL, objectMapper.convertValue(JwtAclDTO.builder()
|
||||
.pub(List.of(subTopic))
|
||||
.sub(List.of(pubTopic))
|
||||
.build(), new TypeReference<Map<String, ?>>() {}))))
|
||||
.setHsiFrequency(1).setOsdFrequency(10));
|
||||
|
||||
if (!reply.getData().getResult().isSuccess()) {
|
||||
throw new RuntimeException("SN: " + param.getDockSn() + "; Error:" + reply.getData().getResult() +
|
||||
"; Failed to enter command flight control mode, please try again later!");
|
||||
}
|
||||
|
||||
refreshAcl(param.getDockSn(), param.getClientId(), pubTopic, subTopic);
|
||||
return JwtAclDTO.builder().sub(List.of(subTopic)).pub(List.of(pubTopic)).build();
|
||||
}
|
||||
|
||||
private void refreshAcl(String dockSn, String clientId, String pubTopic, String subTopic) {
|
||||
this.setDrcModeInRedis(dockSn, clientId);
|
||||
|
||||
// assign acl,Match by clientId. https://www.emqx.io/docs/zh/v4.4/advanced/acl-redis.html
|
||||
// scheme: HSET mqtt_acl:[clientid] [topic] [access]
|
||||
String key = RedisConst.MQTT_ACL_PREFIX + clientId;
|
||||
RedisOpsUtils.hashSet(key, pubTopic, MqttAclAccessEnum.PUB.getValue());
|
||||
RedisOpsUtils.hashSet(key, subTopic, MqttAclAccessEnum.SUB.getValue());
|
||||
RedisOpsUtils.expireKey(key, RedisConst.DRC_MODE_ALIVE_SECOND);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deviceDrcExit(String workspaceId, DrcModeParam param) {
|
||||
if (!deviceService.checkDockDrcMode(param.getDockSn())) {
|
||||
throw new RuntimeException("The dock is not in flight control mode.");
|
||||
}
|
||||
TopicServicesResponse<ServicesReplyData> reply =
|
||||
abstractControlService.drcModeExit(SDKManager.getDeviceSDK(param.getDockSn()));
|
||||
if (!reply.getData().getResult().isSuccess()) {
|
||||
throw new RuntimeException("SN: " + param.getDockSn() + "; Error:" +
|
||||
reply.getData().getResult() + "; Failed to exit command flight control mode, please try again later!");
|
||||
}
|
||||
|
||||
String jobId = waylineRedisService.getPausedWaylineJobId(param.getDockSn());
|
||||
if (StringUtils.hasText(jobId)) {
|
||||
flighttaskService.updateJobStatus(workspaceId, jobId, UpdateJobParam.builder().status(WaylineTaskStatusEnum.RESUME).build());
|
||||
}
|
||||
|
||||
this.delDrcModeInRedis(param.getDockSn());
|
||||
RedisOpsUtils.del(RedisConst.MQTT_ACL_PREFIX + param.getClientId());
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public class GimbalResetImpl extends PayloadCommandsHandler {
|
||||
public GimbalResetImpl(DronePayloadParam param) {
|
||||
super(param);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean valid() {
|
||||
return Objects.nonNull(param.getResetMode());
|
||||
}
|
||||
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.common.util.SpringBeanUtilsTest;
|
||||
import com.central.control.model.param.DronePayloadParam;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.service.IDevicePayloadService;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.dji.sdk.cloudapi.device.OsdCamera;
|
||||
import com.dji.sdk.cloudapi.device.OsdDockDrone;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.4
|
||||
* @date 2023/4/23
|
||||
*/
|
||||
public abstract class PayloadCommandsHandler {
|
||||
|
||||
DronePayloadParam param;
|
||||
|
||||
OsdCamera osdCamera;
|
||||
|
||||
PayloadCommandsHandler(DronePayloadParam param) {
|
||||
this.param = param;
|
||||
}
|
||||
|
||||
public boolean valid() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean canPublish(String deviceSn) {
|
||||
Optional<OsdDockDrone> deviceOpt = SpringBeanUtilsTest.getBean(IDeviceRedisService.class)
|
||||
.getDeviceOsd(deviceSn, OsdDockDrone.class);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
throw new RuntimeException("The device is offline.");
|
||||
}
|
||||
osdCamera = deviceOpt.get().getCameras().stream()
|
||||
.filter(osdCamera -> param.getPayloadIndex().equals(osdCamera.getPayloadIndex().toString()))
|
||||
.findAny()
|
||||
.orElseThrow(() -> new RuntimeException("Did not receive osd information about the camera, please check the cache data."));
|
||||
return true;
|
||||
}
|
||||
|
||||
private String checkDockOnline(String dockSn) {
|
||||
Optional<DeviceDTO> deviceOpt = SpringBeanUtilsTest.getBean(IDeviceRedisService.class).getDeviceOnline(dockSn);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
throw new RuntimeException("The dock is offline.");
|
||||
}
|
||||
return deviceOpt.get().getChildDeviceSn();
|
||||
}
|
||||
|
||||
private void checkDeviceOnline(String deviceSn) {
|
||||
boolean isOnline = SpringBeanUtilsTest.getBean(IDeviceRedisService.class).checkDeviceOnline(deviceSn);
|
||||
if (!isOnline) {
|
||||
throw new RuntimeException("The device is offline.");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkAuthority(String deviceSn) {
|
||||
boolean hasAuthority = SpringBeanUtilsTest.getBean(IDevicePayloadService.class)
|
||||
.checkAuthorityPayload(deviceSn, param.getPayloadIndex());
|
||||
if (!hasAuthority) {
|
||||
throw new RuntimeException("The device does not have payload control authority.");
|
||||
}
|
||||
}
|
||||
|
||||
public final void checkCondition(String dockSn) {
|
||||
if (!valid()) {
|
||||
throw new RuntimeException("illegal argument");
|
||||
}
|
||||
|
||||
String deviceSn = checkDockOnline(dockSn);
|
||||
checkDeviceOnline(deviceSn);
|
||||
checkAuthority(deviceSn);
|
||||
|
||||
if (!canPublish(deviceSn)) {
|
||||
throw new RuntimeException("The current state of the drone does not support this function, please try again later.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.common.util.SpringBeanUtilsTest;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.cloudapi.device.DockModeCodeEnum;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.3
|
||||
* @date 2022/10/27
|
||||
*/
|
||||
public class RemoteDebugHandler {
|
||||
|
||||
public boolean valid() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean canPublish(String sn) {
|
||||
IDeviceService deviceService = SpringBeanUtilsTest.getBean(IDeviceService.class);
|
||||
DockModeCodeEnum dockMode = deviceService.getDockMode(sn);
|
||||
return DockModeCodeEnum.REMOTE_DEBUGGING == dockMode;
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.component.websocket.model.BizCodeEnum;
|
||||
import com.central.component.websocket.service.IWebSocketMessageService;
|
||||
import com.central.control.model.dto.ResultNotifyDTO;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.model.enums.UserTypeEnum;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.dji.sdk.cloudapi.control.*;
|
||||
import com.dji.sdk.cloudapi.control.api.AbstractControlService;
|
||||
import com.dji.sdk.mqtt.MqttReply;
|
||||
import com.dji.sdk.mqtt.events.TopicEventsRequest;
|
||||
import com.dji.sdk.mqtt.events.TopicEventsResponse;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.messaging.MessageHeaders;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.7
|
||||
* @date 2023/7/4
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class SDKControlService extends AbstractControlService {
|
||||
|
||||
@Autowired
|
||||
private IWebSocketMessageService webSocketMessageService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceRedisService deviceRedisService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Override
|
||||
public TopicEventsResponse<MqttReply> flyToPointProgress(TopicEventsRequest<FlyToPointProgress> request, MessageHeaders headers) {
|
||||
String dockSn = request.getGateway();
|
||||
|
||||
Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
log.error("The dock is offline.");
|
||||
return null;
|
||||
}
|
||||
|
||||
FlyToPointProgress eventsReceiver = request.getData();
|
||||
webSocketMessageService.sendBatch(deviceOpt.get().getWorkspaceId(), UserTypeEnum.WEB.getVal(),
|
||||
BizCodeEnum.FLY_TO_POINT_PROGRESS.getCode(),
|
||||
ResultNotifyDTO.builder().sn(dockSn)
|
||||
.message(eventsReceiver.getResult().toString())
|
||||
.result(eventsReceiver.getResult().getCode())
|
||||
.build());
|
||||
return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TopicEventsResponse<MqttReply> takeoffToPointProgress(TopicEventsRequest<TakeoffToPointProgress> request, MessageHeaders headers) {
|
||||
String dockSn = request.getGateway();
|
||||
|
||||
Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
log.error("The dock is offline.");
|
||||
return null;
|
||||
}
|
||||
|
||||
TakeoffToPointProgress eventsReceiver = request.getData();
|
||||
webSocketMessageService.sendBatch(deviceOpt.get().getWorkspaceId(), UserTypeEnum.WEB.getVal(),
|
||||
BizCodeEnum.TAKE_OFF_TO_POINT_PROGRESS.getCode(),
|
||||
ResultNotifyDTO.builder().sn(dockSn)
|
||||
.message(eventsReceiver.getResult().toString())
|
||||
.result(eventsReceiver.getResult().getCode())
|
||||
.build());
|
||||
|
||||
return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TopicEventsResponse<MqttReply> drcStatusNotify(TopicEventsRequest<DrcStatusNotify> request, MessageHeaders headers) {
|
||||
String dockSn = request.getGateway();
|
||||
|
||||
Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
DrcStatusNotify eventsReceiver = request.getData();
|
||||
if (DrcStatusErrorEnum.SUCCESS != eventsReceiver.getResult()) {
|
||||
webSocketMessageService.sendBatch(
|
||||
deviceOpt.get().getWorkspaceId(), UserTypeEnum.WEB.getVal(), BizCodeEnum.DRC_STATUS_NOTIFY.getCode(),
|
||||
ResultNotifyDTO.builder().sn(dockSn)
|
||||
.message(eventsReceiver.getResult().getMessage())
|
||||
.result(eventsReceiver.getResult().getCode()).build());
|
||||
}
|
||||
return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TopicEventsResponse<MqttReply> joystickInvalidNotify(TopicEventsRequest<JoystickInvalidNotify> request, MessageHeaders headers) {
|
||||
String dockSn = request.getGateway();
|
||||
|
||||
Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(dockSn);
|
||||
if (deviceOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JoystickInvalidNotify eventsReceiver = request.getData();
|
||||
webSocketMessageService.sendBatch(
|
||||
deviceOpt.get().getWorkspaceId(), UserTypeEnum.WEB.getVal(), BizCodeEnum.JOYSTICK_INVALID_NOTIFY.getCode(),
|
||||
ResultNotifyDTO.builder().sn(dockSn)
|
||||
.message(eventsReceiver.getReason().getMessage())
|
||||
.result(eventsReceiver.getReason().getVal()).build());
|
||||
return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.central.control.service.impl;
|
||||
|
||||
import com.central.component.mqtt.model.EventsReceiver;
|
||||
import com.central.component.websocket.service.IWebSocketMessageService;
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.model.enums.UserTypeEnum;
|
||||
import com.central.manage.service.IDeviceRedisService;
|
||||
import com.dji.sdk.cloudapi.debug.RemoteDebugProgress;
|
||||
import com.dji.sdk.cloudapi.debug.api.AbstractDebugService;
|
||||
import com.dji.sdk.mqtt.MqttReply;
|
||||
import com.dji.sdk.mqtt.events.EventsDataRequest;
|
||||
import com.dji.sdk.mqtt.events.TopicEventsRequest;
|
||||
import com.dji.sdk.mqtt.events.TopicEventsResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.messaging.MessageHeaders;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.7
|
||||
* @date 2023/7/4
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class SDKRemoteDebug extends AbstractDebugService {
|
||||
|
||||
@Autowired
|
||||
private IWebSocketMessageService webSocketMessageService;
|
||||
|
||||
@Autowired
|
||||
private IDeviceRedisService deviceRedisService;
|
||||
|
||||
@Override
|
||||
public TopicEventsResponse<MqttReply> remoteDebugProgress(TopicEventsRequest<EventsDataRequest<RemoteDebugProgress>> request, MessageHeaders headers) {
|
||||
String sn = request.getGateway();
|
||||
|
||||
EventsReceiver<RemoteDebugProgress> eventsReceiver = new EventsReceiver<RemoteDebugProgress>()
|
||||
.setOutput(request.getData().getOutput()).setResult(request.getData().getResult());
|
||||
eventsReceiver.setBid(request.getBid());
|
||||
eventsReceiver.setSn(sn);
|
||||
|
||||
log.info("SN: {}, {} ===> Control progress: {}", sn, request.getMethod(), eventsReceiver.getOutput().getProgress());
|
||||
|
||||
if (!eventsReceiver.getResult().isSuccess()) {
|
||||
log.error("SN: {}, {} ===> Error: {}", sn, request.getMethod(), eventsReceiver.getResult());
|
||||
}
|
||||
|
||||
Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(sn);
|
||||
|
||||
if (deviceOpt.isEmpty()) {
|
||||
throw new RuntimeException("The device is offline.");
|
||||
}
|
||||
|
||||
DeviceDTO device = deviceOpt.get();
|
||||
webSocketMessageService.sendBatch(device.getWorkspaceId(), UserTypeEnum.WEB.getVal(),
|
||||
request.getMethod(), eventsReceiver);
|
||||
|
||||
return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.manage.model.dto.DeviceDTO;
|
||||
import com.central.manage.model.dto.DeviceFirmwareUpgradeDTO;
|
||||
import com.central.manage.service.IDeviceService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.PaginationData;
|
||||
import com.dji.sdk.exception.CloudSDKErrorEnum;
|
||||
import com.dji.sdk.mqtt.property.PropertySetReplyResultEnum;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/15
|
||||
*/
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/devices")
|
||||
public class DeviceController {
|
||||
|
||||
@Autowired
|
||||
private IDeviceService deviceService;
|
||||
|
||||
/**
|
||||
* Get the topology list of all online devices in one workspace.
|
||||
* @param workspaceId
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices")
|
||||
public HttpResultResponse<List<DeviceDTO>> getDevices(@PathVariable("workspace_id") String workspaceId) {
|
||||
List<DeviceDTO> devicesList = deviceService.getDevicesTopoForWeb(workspaceId);
|
||||
|
||||
return HttpResultResponse.success(devicesList);
|
||||
}
|
||||
|
||||
/**
|
||||
* After binding the device to the workspace, the device data can only be seen on the web.
|
||||
* @param device
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/{device_sn}/binding")
|
||||
public HttpResultResponse bindDevice(@RequestBody DeviceDTO device, @PathVariable("device_sn") String deviceSn) {
|
||||
device.setDeviceSn(deviceSn);
|
||||
boolean isUpd = deviceService.bindDevice(device);
|
||||
return isUpd ? HttpResultResponse.success() : HttpResultResponse.error();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain device information according to device sn.
|
||||
* @param workspaceId
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/{device_sn}")
|
||||
public HttpResultResponse getDevice(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn) {
|
||||
Optional<DeviceDTO> deviceOpt = deviceService.getDeviceBySn(deviceSn);
|
||||
return deviceOpt.isEmpty() ? HttpResultResponse.error("device not found.") : HttpResultResponse.success(deviceOpt.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the binding devices list in one workspace.
|
||||
* @param workspaceId
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/bound")
|
||||
public HttpResultResponse<PaginationData<DeviceDTO>> getBoundDevicesWithDomain(
|
||||
@PathVariable("workspace_id") String workspaceId, Integer domain,
|
||||
@RequestParam(defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "50") Long pageSize) {
|
||||
PaginationData<DeviceDTO> devices = deviceService.getBoundDevicesWithDomain(workspaceId, page, pageSize, domain);
|
||||
|
||||
return HttpResultResponse.success(devices);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removing the binding state of the device.
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@DeleteMapping("/{device_sn}/unbinding")
|
||||
public HttpResultResponse unbindingDevice(@PathVariable("device_sn") String deviceSn) {
|
||||
deviceService.unbindDevice(deviceSn);
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update device information.
|
||||
* @param device
|
||||
* @param workspaceId
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{workspace_id}/devices/{device_sn}")
|
||||
public HttpResultResponse updateDevice(@RequestBody DeviceDTO device,
|
||||
@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn) {
|
||||
device.setDeviceSn(deviceSn);
|
||||
boolean isUpd = deviceService.updateDevice(device);
|
||||
return isUpd ? HttpResultResponse.success() : HttpResultResponse.error();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers offline firmware upgrade tasks.
|
||||
* @param workspaceId
|
||||
* @param upgradeDTOS
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/{workspace_id}/devices/ota")
|
||||
public HttpResultResponse createOtaJob(@PathVariable("workspace_id") String workspaceId,
|
||||
@RequestBody List<DeviceFirmwareUpgradeDTO> upgradeDTOS) {
|
||||
return deviceService.createDeviceOtaJob(workspaceId, upgradeDTOS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the property parameters of the drone.
|
||||
* @param workspaceId
|
||||
* @param dockSn
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{workspace_id}/devices/{device_sn}/property")
|
||||
public HttpResultResponse devicePropertySet(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String dockSn,
|
||||
@RequestBody JsonNode param) {
|
||||
if (param.size() != 1) {
|
||||
return HttpResultResponse.error(CloudSDKErrorEnum.INVALID_PARAMETER);
|
||||
}
|
||||
|
||||
int result = deviceService.devicePropertySet(workspaceId, dockSn, param);
|
||||
return PropertySetReplyResultEnum.SUCCESS.getResult() == result ?
|
||||
HttpResultResponse.success() : HttpResultResponse.error(result, String.valueOf(result));
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.manage.model.dto.DeviceFirmwareDTO;
|
||||
import com.central.manage.model.dto.DeviceFirmwareNoteDTO;
|
||||
import com.central.manage.model.dto.FirmwareFileProperties;
|
||||
import com.central.manage.model.param.DeviceFirmwareQueryParam;
|
||||
import com.central.manage.model.param.DeviceFirmwareUpdateParam;
|
||||
import com.central.manage.model.param.DeviceFirmwareUploadParam;
|
||||
import com.central.manage.service.IDeviceFirmwareService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.PaginationData;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/8/16
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/workspaces")
|
||||
@Validated
|
||||
public class DeviceFirmwareController {
|
||||
|
||||
@Autowired
|
||||
private IDeviceFirmwareService service;
|
||||
|
||||
/**
|
||||
* Get the latest firmware version information for this device model.
|
||||
* @param deviceNames
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/firmware-release-notes/latest")
|
||||
public HttpResultResponse<List<DeviceFirmwareNoteDTO>> getLatestFirmwareNote(@RequestParam("device_name") List<String> deviceNames) {
|
||||
|
||||
List<DeviceFirmwareNoteDTO> releaseNotes = deviceNames.stream()
|
||||
.map(deviceName -> service.getLatestFirmwareReleaseNote(deviceName))
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return HttpResultResponse.success(releaseNotes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query firmware information based on parameters.
|
||||
* @param workspaceId
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/firmwares")
|
||||
public HttpResultResponse<PaginationData<DeviceFirmwareDTO>> getAllFirmwarePagination(
|
||||
@PathVariable("workspace_id") String workspaceId, @Valid DeviceFirmwareQueryParam param) {
|
||||
|
||||
PaginationData<DeviceFirmwareDTO> data = service.getAllFirmwarePagination(workspaceId, param);
|
||||
return HttpResultResponse.success(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import firmware file for device upgrades.
|
||||
* @param request
|
||||
* @param workspaceId
|
||||
* @param file
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/{workspace_id}/firmwares/file/upload")
|
||||
public HttpResultResponse importFirmwareFile(HttpServletRequest request, @PathVariable("workspace_id") String workspaceId,
|
||||
@NotNull(message = "No file received.") MultipartFile file,
|
||||
@Valid DeviceFirmwareUploadParam param) {
|
||||
|
||||
if (!file.getOriginalFilename().endsWith(FirmwareFileProperties.FIRMWARE_FILE_SUFFIX)) {
|
||||
return HttpResultResponse.error("The file format is incorrect.");
|
||||
}
|
||||
|
||||
CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
|
||||
String creator = customClaim.getUsername();
|
||||
|
||||
service.importFirmwareFile(workspaceId, creator, param, file);
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the firmware availability status.
|
||||
* @param workspaceId
|
||||
* @param firmwareId
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{workspace_id}/firmwares/{firmware_id}")
|
||||
public HttpResultResponse changeFirmwareStatus(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("firmware_id") String firmwareId,
|
||||
@Valid @RequestBody DeviceFirmwareUpdateParam param) {
|
||||
|
||||
service.updateFirmwareInfo(DeviceFirmwareDTO.builder()
|
||||
.firmwareId(firmwareId).firmwareStatus(param.getStatus()).build());
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.manage.model.dto.DeviceHmsDTO;
|
||||
import com.central.manage.model.param.DeviceHmsQueryParam;
|
||||
import com.central.manage.service.IDeviceHmsService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.PaginationData;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.1
|
||||
* @date 2022/7/7
|
||||
*/
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/devices")
|
||||
public class DeviceHmsController {
|
||||
|
||||
@Autowired
|
||||
private IDeviceHmsService deviceHmsService;
|
||||
|
||||
/**
|
||||
* Page to query the hms information of the device.
|
||||
* @param param
|
||||
* @param workspaceId
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/hms")
|
||||
public HttpResultResponse<PaginationData<DeviceHmsDTO>> getHmsInformation(DeviceHmsQueryParam param,
|
||||
@PathVariable("workspace_id") String workspaceId) {
|
||||
PaginationData<DeviceHmsDTO> devices = deviceHmsService.getDeviceHmsByParam(param);
|
||||
|
||||
return HttpResultResponse.success(devices);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update unread hms messages to read status.
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{workspace_id}/devices/hms/{device_sn}")
|
||||
public HttpResultResponse updateReadHmsByDeviceSn(@PathVariable("device_sn") String deviceSn) {
|
||||
deviceHmsService.updateUnreadHms(deviceSn);
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get hms messages for a single device.
|
||||
* @param deviceSn
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/hms/{device_sn}")
|
||||
public HttpResultResponse<List<DeviceHmsDTO>> getUnreadHmsByDeviceSn(@PathVariable("device_sn") String deviceSn) {
|
||||
PaginationData<DeviceHmsDTO> paginationData = deviceHmsService.getDeviceHmsByParam(
|
||||
DeviceHmsQueryParam.builder()
|
||||
.deviceSn(new HashSet<>(Set.of(deviceSn)))
|
||||
.updateTime(0L)
|
||||
.build());
|
||||
return HttpResultResponse.success(paginationData.getList());
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.manage.model.dto.DeviceLogsDTO;
|
||||
import com.central.manage.model.param.DeviceLogsCreateParam;
|
||||
import com.central.manage.model.param.DeviceLogsGetParam;
|
||||
import com.central.manage.model.param.DeviceLogsQueryParam;
|
||||
import com.central.manage.service.IDeviceLogsService;
|
||||
import com.dji.sdk.cloudapi.log.FileUploadUpdateRequest;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.PaginationData;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URL;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/9/7
|
||||
*/
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/workspaces")
|
||||
public class DeviceLogsController {
|
||||
|
||||
@Autowired
|
||||
private IDeviceLogsService deviceLogsService;
|
||||
|
||||
/**
|
||||
* Obtain the device upload log list by paging according to the query parameters.
|
||||
* @param workspaceId
|
||||
* @param deviceSn
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/{device_sn}/logs-uploaded")
|
||||
public HttpResultResponse getUploadedLogs(DeviceLogsQueryParam param, @PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn) {
|
||||
PaginationData<DeviceLogsDTO> data = deviceLogsService.getUploadedLogs(deviceSn, param);
|
||||
return HttpResultResponse.success(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of log files that can be uploaded in real time.
|
||||
* @param workspaceId
|
||||
* @param deviceSn
|
||||
* @param param
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/devices/{device_sn}/logs")
|
||||
public HttpResultResponse getLogsBySn(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn,
|
||||
DeviceLogsGetParam param) {
|
||||
return deviceLogsService.getRealTimeLogs(deviceSn, param.getDomainList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate a log upload request to the gateway.
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/{workspace_id}/devices/{device_sn}/logs")
|
||||
public HttpResultResponse uploadLogs(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn,
|
||||
HttpServletRequest request, @RequestBody DeviceLogsCreateParam param) {
|
||||
|
||||
CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
|
||||
|
||||
return deviceLogsService.pushFileUpload(customClaim.getUsername(), deviceSn, param);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel logs file upload.
|
||||
* @return
|
||||
*/
|
||||
@DeleteMapping("/{workspace_id}/devices/{device_sn}/logs")
|
||||
public HttpResultResponse cancelUploadedLogs(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn,
|
||||
@RequestBody FileUploadUpdateRequest param) {
|
||||
|
||||
return deviceLogsService.pushUpdateFile(deviceSn, param);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete upload history.
|
||||
* @return
|
||||
*/
|
||||
@DeleteMapping("/{workspace_id}/devices/{device_sn}/logs/{logs_id}")
|
||||
public HttpResultResponse deleteUploadedLogs(@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("device_sn") String deviceSn,
|
||||
@PathVariable("logs_id") String logsId) {
|
||||
deviceLogsService.deleteLogs(deviceSn, logsId);
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
/**
|
||||
* Query the download address of the file according to the wayline file id,
|
||||
* and redirect to this address directly for download.
|
||||
* @param workspaceId
|
||||
* @param fileId
|
||||
* @param logsId
|
||||
* @param response
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/logs/{logs_id}/url/{file_id}")
|
||||
public HttpResultResponse getFileUrl(@PathVariable(name = "workspace_id") String workspaceId,
|
||||
@PathVariable(name = "file_id") String fileId,
|
||||
@PathVariable(name = "logs_id") String logsId, HttpServletResponse response) {
|
||||
|
||||
try {
|
||||
URL url = deviceLogsService.getLogsFileUrl(logsId, fileId);
|
||||
return HttpResultResponse.success(url.toString());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to get the logs file download address.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return HttpResultResponse.error("Failed to get the logs file download address.");
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.manage.model.dto.CapacityDeviceDTO;
|
||||
import com.central.manage.model.dto.LiveTypeDTO;
|
||||
import com.central.manage.service.ILiveStreamService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/19
|
||||
*/
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/live")
|
||||
public class LiveStreamController {
|
||||
|
||||
@Autowired
|
||||
private ILiveStreamService liveStreamService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper mapper;
|
||||
|
||||
/**
|
||||
* Get live capability data of all drones in the current user's workspace from the database.
|
||||
* @param request
|
||||
* @return live capability
|
||||
*/
|
||||
@GetMapping("/capacity")
|
||||
public HttpResultResponse<List<CapacityDeviceDTO>> getLiveCapacity(HttpServletRequest request) {
|
||||
// Get information about the current user.
|
||||
CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
|
||||
|
||||
List<CapacityDeviceDTO> liveCapacity = liveStreamService.getLiveCapacity(customClaim.getWorkspaceId());
|
||||
|
||||
return HttpResultResponse.success(liveCapacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live streaming according to the parameters passed in from the web side.
|
||||
* @param liveParam Live streaming parameters.
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/streams/start")
|
||||
public HttpResultResponse liveStart(@RequestBody LiveTypeDTO liveParam) {
|
||||
return liveStreamService.liveStart(liveParam);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop live streaming according to the parameters passed in from the web side.
|
||||
* @param liveParam Live streaming parameters.
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/streams/stop")
|
||||
public HttpResultResponse liveStop(@RequestBody LiveTypeDTO liveParam) {
|
||||
return liveStreamService.liveStop(liveParam.getVideoId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the quality of the live streaming according to the parameters passed in from the web side.
|
||||
* @param liveParam Live streaming parameters.
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/streams/update")
|
||||
public HttpResultResponse liveSetQuality(@RequestBody LiveTypeDTO liveParam) {
|
||||
return liveStreamService.liveSetQuality(liveParam);
|
||||
}
|
||||
|
||||
@PostMapping("/streams/switch")
|
||||
public HttpResultResponse liveLensChange(@RequestBody LiveTypeDTO liveParam) {
|
||||
return liveStreamService.liveLensChange(liveParam);
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.error.CommonErrorEnum;
|
||||
import com.central.manage.model.dto.UserDTO;
|
||||
import com.central.manage.model.dto.UserLoginDTO;
|
||||
import com.central.manage.service.IUserService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.central.component.AuthInterceptor.PARAM_TOKEN;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}")
|
||||
public class LoginController {
|
||||
|
||||
@Autowired
|
||||
private IUserService userService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public HttpResultResponse login(@RequestBody UserLoginDTO loginDTO) {
|
||||
|
||||
String username = loginDTO.getUsername();
|
||||
String password = loginDTO.getPassword();
|
||||
return userService.userLogin(username, password, loginDTO.getFlag());
|
||||
}
|
||||
|
||||
@PostMapping("/token/refresh")
|
||||
public HttpResultResponse refreshToken(HttpServletRequest request, HttpServletResponse response) {
|
||||
String token = request.getHeader(PARAM_TOKEN);
|
||||
Optional<UserDTO> user = userService.refreshToken(token);
|
||||
|
||||
if (user.isEmpty()) {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
return HttpResultResponse.error(CommonErrorEnum.NO_TOKEN.getMessage());
|
||||
}
|
||||
|
||||
return HttpResultResponse.success(user.get());
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.manage.service.ITopologyService;
|
||||
import com.dji.sdk.cloudapi.tsa.TopologyList;
|
||||
import com.dji.sdk.cloudapi.tsa.TopologyResponse;
|
||||
import com.dji.sdk.cloudapi.tsa.api.IHttpTsaService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 0.2
|
||||
* @date 2021/12/8
|
||||
*/
|
||||
@RestController
|
||||
public class TopologyController implements IHttpTsaService {
|
||||
|
||||
@Autowired
|
||||
private ITopologyService topologyService;
|
||||
|
||||
|
||||
/**
|
||||
* Get the topology list of all devices in the current user workspace for pilot display.
|
||||
* @param workspaceId
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public HttpResultResponse<TopologyResponse> obtainDeviceTopologyList(String workspaceId, HttpServletRequest req, HttpServletResponse rsp) {
|
||||
List<TopologyList> topologyList = topologyService.getDeviceTopology(workspaceId);
|
||||
return HttpResultResponse.success(new TopologyResponse().setList(topologyList));
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.manage.model.dto.UserListDTO;
|
||||
import com.central.manage.service.IUserService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import com.dji.sdk.common.PaginationData;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
|
||||
@RestController
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/users")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private IUserService userService;
|
||||
|
||||
/**
|
||||
* Query the information of the current user.
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/current")
|
||||
public HttpResultResponse getCurrentUserInfo(HttpServletRequest request) {
|
||||
CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
|
||||
return userService.getUserByUsername(customClaim.getUsername(), customClaim.getWorkspaceId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Paging to query all users in a workspace.
|
||||
* @param page current page
|
||||
* @param pageSize
|
||||
* @param workspaceId
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{workspace_id}/users")
|
||||
public HttpResultResponse<PaginationData<UserListDTO>> getUsers(@RequestParam(defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "50") Long pageSize,
|
||||
@PathVariable("workspace_id") String workspaceId) {
|
||||
PaginationData<UserListDTO> paginationData = userService.getUsersByWorkspaceId(page, pageSize, workspaceId);
|
||||
return HttpResultResponse.success(paginationData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify user information. Only mqtt account information is included, nothing else can be modified.
|
||||
* @param user
|
||||
* @param workspaceId
|
||||
* @param userId
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{workspace_id}/users/{user_id}")
|
||||
public HttpResultResponse updateUser(@RequestBody UserListDTO user,
|
||||
@PathVariable("workspace_id") String workspaceId,
|
||||
@PathVariable("user_id") String userId) {
|
||||
|
||||
userService.updateUser(workspaceId, userId, user);
|
||||
return HttpResultResponse.success();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.central.manage.controller;
|
||||
|
||||
import com.central.common.model.CustomClaim;
|
||||
import com.central.manage.model.dto.WorkspaceDTO;
|
||||
import com.central.manage.service.IWorkspaceService;
|
||||
import com.dji.sdk.common.HttpResultResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.central.component.AuthInterceptor.TOKEN_CLAIM;
|
||||
|
||||
/**
|
||||
* @author sean.zhou
|
||||
* @version 0.1
|
||||
* @date 2021/11/23
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("${url.manage.prefix}${url.manage.version}/workspaces")
|
||||
public class WorkspaceController {
|
||||
|
||||
@Autowired
|
||||
private IWorkspaceService workspaceService;
|
||||
|
||||
/**
|
||||
* Gets information about the workspace that the current user is in.
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/current")
|
||||
public HttpResultResponse getCurrentWorkspace(HttpServletRequest request) {
|
||||
CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
|
||||
Optional<WorkspaceDTO> workspaceOpt = workspaceService.getWorkspaceByWorkspaceId(customClaim.getWorkspaceId());
|
||||
|
||||
return workspaceOpt.isEmpty() ? HttpResultResponse.error() : HttpResultResponse.success(workspaceOpt.get());
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.central.manage.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.manage.model.entity.DeviceDictionaryEntity;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/15
|
||||
* @version 0.1
|
||||
*/
|
||||
public interface IDeviceDictionaryMapper extends BaseMapper<DeviceDictionaryEntity> {
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.central.manage.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Constants;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.manage.model.entity.DeviceFirmwareEntity;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/8/16
|
||||
*/
|
||||
public interface IDeviceFirmwareMapper extends BaseMapper<DeviceFirmwareEntity> {
|
||||
String sql = "<script> \n" +
|
||||
"SELECT \n" +
|
||||
" * \n" +
|
||||
"from \n" +
|
||||
" (\n" +
|
||||
" select \n" +
|
||||
" a.*, \n" +
|
||||
" group_concat(b.device_name) device_name \n" +
|
||||
" from \n" +
|
||||
" manage_device_firmware a \n" +
|
||||
" join manage_firmware_model b on a.firmware_id = b.firmware_id \n" +
|
||||
" <if test='device_name != null and device_name != \"\"'> \n" +
|
||||
" and b.device_name = #{device_name} \n" +
|
||||
" </if> \n" +
|
||||
" group by firmware_id \n" +
|
||||
" ) c ${ew.customSqlSegment} \n";
|
||||
|
||||
@Select(sql + "</script>")
|
||||
Page<DeviceFirmwareEntity> selectPage(Page page, @Param(Constants.WRAPPER)Wrapper<DeviceFirmwareEntity> wrapper, @Param("device_name") String deviceName);
|
||||
|
||||
@Select(sql + " limit 1 </script>")
|
||||
DeviceFirmwareEntity selectOne(@Param(Constants.WRAPPER)Wrapper<DeviceFirmwareEntity> wrapper, @Param("device_name") String deviceName);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.central.manage.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.manage.model.entity.DeviceHmsEntity;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.1
|
||||
* @date 2022/7/6
|
||||
*/
|
||||
public interface IDeviceHmsMapper extends BaseMapper<DeviceHmsEntity> {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.central.manage.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.manage.model.entity.DeviceLogsEntity;
|
||||
|
||||
/**
|
||||
* @author sean
|
||||
* @version 1.2
|
||||
* @date 2022/9/7
|
||||
*/
|
||||
public interface IDeviceLogsMapper extends BaseMapper<DeviceLogsEntity> {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.central.manage.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.manage.model.entity.DeviceEntity;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author sean.zhou
|
||||
* @date 2021/11/10
|
||||
* @version 0.1
|
||||
*/
|
||||
public interface IDeviceMapper extends BaseMapper<DeviceEntity> {
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user