无人机项目后端代码
sean.zhou
2022-03-21 17835b967b48f2676cce3bbed081c6580602ee1c
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package com.dji.sample.manage.service.impl;
 
import com.dji.sample.common.error.LiveErrorEnum;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.component.mqtt.model.CommonTopicReceiver;
import com.dji.sample.component.mqtt.model.CommonTopicResponse;
import com.dji.sample.component.mqtt.service.IMessageSenderService;
import com.dji.sample.manage.model.Chan;
import com.dji.sample.manage.model.dto.*;
import com.dji.sample.manage.model.enums.DeviceDomainEnum;
import com.dji.sample.manage.model.enums.LiveMethodEnum;
import com.dji.sample.manage.model.enums.LiveUrlTypeEnum;
import com.dji.sample.manage.model.enums.LiveVideoQualityEnum;
import com.dji.sample.manage.model.param.DeviceQueryParam;
import com.dji.sample.manage.model.receiver.CapacityDeviceReceiver;
import com.dji.sample.manage.model.receiver.ServiceReplyReceiver;
import com.dji.sample.manage.service.ICapacityCameraService;
import com.dji.sample.manage.service.IDeviceService;
import com.dji.sample.manage.service.ILiveStreamService;
import com.dji.sample.manage.service.IWorkspaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
 
import static com.dji.sample.component.mqtt.model.TopicConst.*;
 
/**
 * @author sean.zhou
 * @date 2021/11/22
 * @version 0.1
 */
@Service
@Transactional
public class LiveStreamServiceImpl implements ILiveStreamService {
 
    @Autowired
    private ICapacityCameraService capacityCameraService;
 
    @Autowired
    private IDeviceService deviceService;
 
    @Autowired
    private IWorkspaceService workspaceService;
 
    @Autowired
    private IMessageSenderService messageSender;
 
    @Override
    public List<CapacityDeviceDTO> getLiveCapacity(String workspaceId) {
 
        // Query all drone data in this workspace.
        List<DeviceDTO> devicesList = deviceService.getDevicesByParams(
                DeviceQueryParam.builder()
                        .workspaceId(workspaceId)
                        .domain(DeviceDomainEnum.SUB_DEVICE.getVal())
                        .build());
 
        List<CapacityDeviceDTO> capacityDevicesList = new ArrayList<>();
        // Query the live capability of each drone.
        devicesList.forEach(device -> capacityDevicesList.add(CapacityDeviceDTO.builder()
                .name(device.getDeviceName())
                .sn(device.getDeviceSn())
                .camerasList(capacityCameraService.getCapacityCameraByDeviceSn(device.getDeviceSn()))
                .build()));
 
        return capacityDevicesList;
    }
 
    @Override
    public Boolean saveLiveCapacity(CapacityDeviceReceiver capacityDeviceReceiver) {
        return capacityCameraService.saveCapacityCameraReceiverList(
                capacityDeviceReceiver.getCameraList(),
                capacityDeviceReceiver.getSn());
    }
 
    @Override
    public ResponseResult liveStart(LiveTypeDTO liveParam) {
        // Check if this lens is available live.
        ResponseResult responseResult = this.checkBeforeLive(liveParam.getVideoId());
        if (responseResult.getCode() != 0) {
            return responseResult;
        }
 
        List<DeviceDTO> data = (List<DeviceDTO>)responseResult.getData();
        // target topic
        String respTopic = THING_MODEL_PRE + PRODUCT +
                data.get(0).getDeviceSn() + SERVICES_SUF;
        Optional<ServiceReplyReceiver> receiveReplyOpt = this.publishLiveStart(respTopic, liveParam);
 
        if (receiveReplyOpt.isEmpty()) {
            return ResponseResult.error(LiveErrorEnum.NO_REPLY);
        }
        if (receiveReplyOpt.get().getResult() != 0) {
            return ResponseResult.error(LiveErrorEnum.find(receiveReplyOpt.get().getResult()));
        }
 
        LiveUrlTypeEnum urlType = LiveUrlTypeEnum.find(liveParam.getUrlType());
        LiveDTO live = new LiveDTO();
 
        switch (urlType) {
            case RTMP:
                live.setUrl(liveParam.getUrl().replace("rtmp", "webrtc"));
                break;
            case GB28181:
                LiveUrlGB28181DTO gb28181 = urlToGB28181(liveParam.getUrl());
                live.setUrl(new StringBuilder()
                        .append("webrtc://")
                        .append(gb28181.getServerIP())
                        .append("/live/")
                        .append(gb28181.getAgentID())
                        .append("@")
                        .append(gb28181.getChannel())
                        .toString());
                break;
            case RTSP:
                String url = receiveReplyOpt.get().getInfo();
                this.resolveUrlUser(url, live);
                break;
            case UNKNOWN:
                return ResponseResult.error(LiveErrorEnum.URL_TYPE_NOT_SUPPORTED);
        }
 
        return ResponseResult.success(live);
    }
 
    @Override
    public ResponseResult liveStop(String videoId) {
        ResponseResult<List<DeviceDTO>> responseResult = this.checkBeforeLive(videoId);
        if (responseResult.getCode() != 0) {
            return responseResult;
        }
 
        String respTopic = THING_MODEL_PRE + PRODUCT + responseResult.getData().get(0).getDeviceSn() + SERVICES_SUF;
 
        Optional<ServiceReplyReceiver> receiveReplyOpt = this.publishLiveStop(respTopic, videoId);
        if (receiveReplyOpt.isEmpty()) {
            return ResponseResult.error(LiveErrorEnum.NO_REPLY);
        }
        if (receiveReplyOpt.get().getResult() != 0) {
            return ResponseResult.error(LiveErrorEnum.find(receiveReplyOpt.get().getResult()));
        }
 
        return ResponseResult.success();
    }
 
    @Override
    public ResponseResult liveSetQuality(LiveTypeDTO liveParam) {
        if (liveParam.getVideoQuality() == null ||
                LiveVideoQualityEnum.UNKNOWN == LiveVideoQualityEnum.find(liveParam.getVideoQuality())) {
            return ResponseResult.error(LiveErrorEnum.ERROR_PARAMETERS);
        }
 
        ResponseResult<List<DeviceDTO>> responseResult = this.checkBeforeLive(liveParam.getVideoId());
 
        if (responseResult.getCode() != 0) {
            return responseResult;
        }
 
        String respTopic = THING_MODEL_PRE + PRODUCT + responseResult.getData().get(0).getDeviceSn() + SERVICES_SUF;
 
        Optional<ServiceReplyReceiver> receiveReplyOpt = this.publishLiveSetQuality(respTopic, liveParam);
        if (receiveReplyOpt.isEmpty()) {
            return ResponseResult.error(LiveErrorEnum.NO_REPLY);
        }
        if (receiveReplyOpt.get().getResult() != 0) {
            return ResponseResult.error(LiveErrorEnum.find(receiveReplyOpt.get().getResult()));
        }
 
        return ResponseResult.success();
    }
 
    /**
     * Check if this lens is available live.
     * @param videoId
     * @return
     */
    private ResponseResult checkBeforeLive(String videoId) {
        String[] videoIdArr = videoId.split("/");
        // drone sn / enumeration value of the location where the payload is mounted / payload lens
        if (videoIdArr.length != 3) {
            return ResponseResult.error(LiveErrorEnum.ERROR_PARAMETERS);
        }
 
        List<DeviceDTO> gatewayList = deviceService.getDevicesByParams(
                DeviceQueryParam.builder()
                        .childSn(videoIdArr[0])
                        .build());
        // Check if the gateway device connected to this drone exists
        if (gatewayList.isEmpty()) {
            return ResponseResult.error(LiveErrorEnum.NO_FLIGHT_CONTROL);
        }
        return ResponseResult.success(gatewayList);
    }
 
    /**
     * When using rtsp live, the account and password are parsed from the information returned by the pilot.
     * @param url
     * @param live
     */
    private void resolveUrlUser(String url, LiveDTO live) {
        if (!StringUtils.hasText(url)) {
            return;
        }
        int start = url.indexOf("//");
        int end = url.lastIndexOf("@");
        String user = url.substring(start + 2, end);
 
        url = url.replace(user + "@", "");
        String[] userArr = user.split(":");
        live.setUsername(userArr[0]);
        live.setPassword(userArr[1]);
        live.setUrl(url);
    }
 
    /**
     * When using GB28181 live, url parameters are resolved into objects.
     * @param url
     * @return
     */
    private LiveUrlGB28181DTO urlToGB28181(String url) {
        String[] arr = url.split("\\=|\\&");
        LiveUrlGB28181DTO gb28181 = new LiveUrlGB28181DTO();
        try {
            Class<LiveUrlGB28181DTO> clazz = LiveUrlGB28181DTO.class;
            for (int i = 0; i < arr.length - 1; i += 2) {
                Field field = clazz.getDeclaredField(arr[i]);
                field.setAccessible(true);
 
                if (field.getType().equals(Integer.class)) {
                    field.set(gb28181, Integer.valueOf(arr[i + 1]));
                    continue;
                }
                field.set(gb28181, arr[i + 1]);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return gb28181;
    }
 
    /**
     * Send a message to the pilot via mqtt to start the live streaming.
     * @param topic
     * @param liveParam
     * @return
     */
    private Optional<ServiceReplyReceiver> publishLiveStart(String topic, LiveTypeDTO liveParam) {
        CommonTopicResponse<LiveTypeDTO> response = new CommonTopicResponse<>();
        response.setTid(UUID.randomUUID().toString());
        response.setBid(UUID.randomUUID().toString());
        response.setData(liveParam);
        response.setMethod(LiveMethodEnum.LIVE_START_PUSH.getMethod());
 
        return this.publishLive(topic, response);
    }
 
    /**
     * Send a message to the pilot via mqtt to set quality.
     * @param respTopic
     * @param liveParam
     * @return
     */
    private Optional<ServiceReplyReceiver> publishLiveSetQuality(String respTopic, LiveTypeDTO liveParam) {
        Map<String, Object> data = new ConcurrentHashMap<>(Map.of(
                "video_id", liveParam.getVideoId(),
                "video_quality", liveParam.getVideoQuality()));
        CommonTopicResponse<Map<String, Object>> response = new CommonTopicResponse<>();
        response.setTid(UUID.randomUUID().toString());
        response.setBid(UUID.randomUUID().toString());
        response.setMethod(LiveMethodEnum.LIVE_SET_QUALITY.getMethod());
        response.setData(data);
 
        return this.publishLive(respTopic, response);
    }
 
    /**
     * Send a message to the pilot via mqtt to stop the live streaming.
     * @param topic
     * @param videoId
     * @return
     */
    private Optional<ServiceReplyReceiver> publishLiveStop(String topic, String videoId) {
        Map<String, String> data = new ConcurrentHashMap<>(Map.of("video_id", videoId));
        CommonTopicResponse<Map<String, String>> response = new CommonTopicResponse<>();
        response.setTid(UUID.randomUUID().toString());
        response.setBid(UUID.randomUUID().toString());
        response.setData(data);
        response.setMethod(LiveMethodEnum.LIVE_STOP_PUSH.getMethod());
 
        return this.publishLive(topic, response);
    }
 
    /**
     * Send live streaming start message and receive a response at the same time
     * @param topic
     * @param response  notification of whether the start is successful.
     * @return
     */
    private Optional<ServiceReplyReceiver> publishLive(String topic, CommonTopicResponse response) {
        AtomicInteger time = new AtomicInteger(0);
        // Retry three times
        while (time.getAndIncrement() < 3) {
            messageSender.publish(topic, response);
 
            Chan<CommonTopicReceiver<ServiceReplyReceiver>> chan = Chan.getInstance();
            // If the message is not received in 0.5 seconds then resend it again.
            CommonTopicReceiver<ServiceReplyReceiver> receiver = chan.get(response.getMethod());
            if (receiver == null) {
                continue;
            }
            // Need to match tid and bid.
            if (receiver.getTid().equals(response.getTid()) &&
                    receiver.getBid().equals(response.getBid())) {
                return Optional.ofNullable(receiver.getData());
            }
        }
        return Optional.empty();
    }
 
}