package com.ard.work.service.impl;
|
|
import com.ard.common.core.domain.model.LoginUser;
|
import com.ard.common.utils.SecurityUtils;
|
import com.ard.work.domain.cache.UavStateCache;
|
import com.ard.work.domain.dto.control.SpeedControlDTO;
|
import com.ard.work.domain.dto.state.UavState;
|
import com.ard.work.service.ITyService;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.stereotype.Service;
|
|
import javax.annotation.Resource;
|
import java.util.Map;
|
import java.util.concurrent.*;
|
|
@Service
|
@Slf4j
|
public class GimbalSpeedService {
|
|
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
|
|
@Resource
|
private ITyService tyService;
|
|
public synchronized void startControl(SpeedControlDTO speed) {
|
String boxSn = speed.getBoxSn();
|
if (tasks.containsKey(boxSn)) {
|
return;
|
}
|
LoginUser loginUser = SecurityUtils.getLoginUser();// 主线程获取
|
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
|
double currentYaw = getCurrentYaw(boxSn);
|
if ((speed.getYawSpeed() < 0 && currentYaw <= -180) ||
|
(speed.getYawSpeed() > 0 && currentYaw >= 180)) {
|
stopControl(boxSn);
|
return;
|
}
|
try {
|
// 在定时任务线程设置用户上下文
|
// 手动设置 SecurityContext
|
SecurityContextHolder.getContext().setAuthentication(
|
new UsernamePasswordAuthenticationToken(
|
loginUser, null, loginUser.getAuthorities())
|
);
|
Boolean b = tyService.speedControl(speed);
|
log.warn("speedControl result:{}", b);
|
} catch (Exception e) {
|
log.error(e.getMessage());
|
}
|
|
}, 0, 200, TimeUnit.MILLISECONDS);
|
|
tasks.put(boxSn, future);
|
}
|
|
public synchronized void stopControl(String boxSn) {
|
ScheduledFuture<?> future = tasks.remove(boxSn);
|
if (future != null) {
|
future.cancel(false);
|
}
|
}
|
|
private double getCurrentYaw(String boxSn) {
|
UavState uavState = UavStateCache.get(boxSn);
|
if(uavState==null)
|
{
|
return 0;
|
}
|
return uavState.getPtzState().getYaw();
|
}
|
}
|