Xiajijian
2025-10-28 502730fd95761286a0bd530435d54217d9e4db35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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();
    }
}