rain
2024-08-07 800cd06bd490444adc45e1d1e5d31ddba9ed9659
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package com.dji.sample.droneairport.service.impl;
 
 
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.component.redis.RedisOpsUtils;
import com.dji.sample.droneairport.dao.DeviceExpanSionDao;
import com.dji.sample.droneairport.model.Entity.DeviceExpanSionEntity;
import com.dji.sample.droneairport.model.dto.AddDeviceDto;
import com.dji.sample.droneairport.model.dto.DroneStateDto;
import com.dji.sample.droneairport.model.dto.RegistDto;
import com.dji.sample.droneairport.service.RegistService;
import com.dji.sample.droneairport.utils.AuthUtil;
import com.dji.sample.droneairport.utils.SM2.Utils;
import com.dji.sample.droneairport.utils.SM4Util;
import com.dji.sample.manage.model.receiver.OsdSubDeviceReceiver;
import com.dji.sample.manage.service.IDeviceRedisService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
 
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Service
public class RegistServiceImpl implements RegistService {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private IDeviceRedisService redisService;
    @Autowired
    private DeviceExpanSionDao expanSionDao;
 
    public String registPort(DeviceExpanSionEntity airport) {
        try {
            RegistDto registDto = airportEntityToDto(airport);
            // 构建请求体
            String jsonBody = buildRequestBody(registDto);
            // 设置请求头
            String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-lc-token", AuthUtil.getToken());
            headers.set("x-lc-secret", Utils.hexToBase64(Utils.encrypt("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98")));
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    "https://xcx.geoway.com.cn:8033/v1/droneAirport/RegistService",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);
            return response.getBody();
 
        } catch (Exception e) {
            // 异常处理
            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
        }
    }
 
    private String buildRequestBody(RegistDto dto) {
        try {
            return objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("数据有误", e);
        }
    }
 
    @Override
    public String addDrone(String workspaceId) {
        try {
            DeviceExpanSionEntity airport = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 0));
            DeviceExpanSionEntity drone = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 1));
            AddDeviceDto dto = deviceEntityToDto(drone);
            // 构建请求体
            String jsonBody = buildRequestBody(dto);
            String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
            String secret = enSM2("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98");
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-lc-token", AuthUtil.getToken());
            headers.set("x-lc-secret", secret);
 
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
 
            // 发送请求
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.postForObject("https://xcx.geoway.com.cn:8033/v1/droneAirport/addDevice", requestEntity, String.class);
            registPort(airport);
            return response;
 
        } catch (Exception e) {
            // 异常处理
            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
        }
    }
 
    @Override
    public ResponseResult getDroneState(String deviceId) throws Exception {
        DroneStateDto data = getAirportFromCache(deviceId);
        String json = JSON.toJSONString(data);
        String SM4Screct = SM4Util.encrypt("jsimjrby3wqb7dbq", json);
        String SM2Screct = enSM2(SM4Screct, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
        return ResponseResult.success(SM2Screct);
    }
 
    @Override
    public ResponseResult authorization(String base64, String enSm4) throws Exception {
        String sm4Secrect = deSM2(enSm4, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
        JSONObject jsonObject = new JSONObject(decryptedJson);
        String deviceId = jsonObject.getStr("deviceid");
        boolean online = redisService.checkDeviceOnline(deviceId);
        if (online) {
            return ResponseResult.success(200, "无人机机场授权成功!", "");
        }
        return ResponseResult.error(500, "无人机机场授权失败!");
    }
 
    private String buildRequestBody(AddDeviceDto dto) {
        try {
            return objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("数据有误", e);
        }
    }
 
 
    public static String enSM2(String data, String pubKey) throws InvalidCipherTextException, IOException {
        String encrypt = Utils.encrypt(data, pubKey);
        encrypt = Utils.hexToBase64(encrypt);
        return encrypt;
    }
 
    public static String deSM2(String Base64, String priKey) throws Exception {
        String hex = Utils.convertBase64ToHex(Base64);
        return Utils.decrypt(hex, priKey);
    }
 
    public static void main(String[] args) throws Exception {
        System.out.println(enSM2("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98"));
        System.out.println(deSM2("BK010WH/Ax++jp57tWA4eHwbB26eqiG7bwmDfzaEGAtA6XN6/lQDt34mL0x4l4fEIOmQSzVfMqt4SV901gjzwf19mAeuPfM8AuCqCZsWZ9QU1bEx5ZqMIUDlFn9ngEbSbZ8qb1ERDvYtaMN5YE+9uI8=", "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D"));
        System.out.println(createKey());
    }
 
    public static Map<String, String> createKey() throws NoSuchAlgorithmException {
        Map<String, String> keyPair = Utils.createKeyPair();
        Map<String, String> newKey = new HashMap<>();
        newKey.put("publicKey", keyPair.get("pbcky"));
        newKey.put("privateKey", keyPair.get("pveky"));
        return newKey;
    }
 
    public AddDeviceDto deviceEntityToDto(DeviceExpanSionEntity entity) {
        AddDeviceDto.AddDeviceDtoBuilder builder = AddDeviceDto.builder();
        if (entity != null) {
            builder.brand(entity.getBrand())
                    .height(entity.getHeight())
                    .longitude(entity.getLongitude())
                    .latitude(entity.getLatitude())
                    .radius(entity.getRadius())
                    .regioncode(entity.getRegioncode())
                    .deviceid(entity.getDeviceId())
                    .model(entity.getModel())
                    .build();
        }
        return builder.build();
    }
 
    public RegistDto airportEntityToDto(DeviceExpanSionEntity entity) {
        RegistDto.RegistDtoBuilder builder = RegistDto.builder();
        if (entity != null) {
            builder.serviceUrl(entity.getServiceUrl())
                    .contacts(entity.getContracts())
                    .phone(entity.getPhone())
                    .liveStreamPluginUrl(entity.getLiveStreamPluginUrl())
                    .build();
        }
        return builder.build();
    }
 
    public OsdSubDeviceReceiver getDroneFromCache(String sn) {
        String key = "osd:" + sn;
        return (OsdSubDeviceReceiver) RedisOpsUtils.get(key);
    }
 
 
    public DroneStateDto getAirportFromCache(String deviceId) {
        OsdSubDeviceReceiver receiver = getDroneFromCache(deviceId);
        DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
        builder.gimbalYal(receiver.getAttitudeHead())
                .gimbalPitch(receiver.getAttitudePitch())
                .batteryCapacityPercent(receiver.getBattery().getCapacityPercent())
                .height(receiver.getHeight())
                .latitude(receiver.getLatitude())
                .longitude(receiver.getLongitude())
                .modeCode(0)
                .elevation(receiver.getElevation())
                .gpsState(2)
                .build();
        return builder.build();
    }
}