chengf
2025-10-28 2807cca4b6f2e8af204d798679dcee78e695ee28
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/*
package com.ruoyi.business.aidetection.config;
 
*/
/**
 * @Author:yuankun
 * @Package:com.ruoyi.business.aidetection.config
 * @Project:ruoyi-vue-service
 * @name:Analyzer
 * @Date:2024/4/9 21:24
 * @Filename:Analyzer
 *//*
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
 
@Component
@Data
@Slf4j
public class Analyzer {
    @Autowired
    private ReadConfig readConfig;
    private String analyzerHost;
    private int timeout=1;
    private boolean analyzerServerState=false;
 
    public Analyzer(ReadConfig readConfig) {
        this.readConfig=readConfig;
        this.analyzerHost=readConfig.getAnalyzerHost();
    }
 
 
    public Map<String,Object> controls() {
        boolean state = false;
        String msg = "error";
        JSONArray data = new JSONArray();
 
        try {
            URL url = new URL(analyzerHost + "/api/controls");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(timeout * 1000);
            connection.setDoOutput(true);
 
            JSONObject requestData = new JSONObject();
 
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestData.toString().getBytes());
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
 
                JSONObject responseJson = new JSONObject(response.toString());
                msg = responseJson.getString("msg");
                if (responseJson.getInt("code") == 1000) {
                    JSONArray responseData = responseJson.getJSONArray("data");
                    if (responseData != null) {
                        data = responseData;
                    }
                    state = true;
                }
            } else {
                msg = "status_code=" + responseCode;
            }
 
            connection.disconnect();
            analyzerServerState = true;
        } catch (Exception e) {
            analyzerServerState = false;
            e.printStackTrace();
            msg = e.toString();
        }
        Map<String,Object> map=new HashMap<>();
        map.put("state", state);
        map.put("msg", msg);
        map.put("data", data);
        return map;
    }
 
    public Map<String,Object> control(String code) {
        boolean state = false;
        String msg = "error";
        JSONObject control = new JSONObject();
 
        try {
            URL url = new URL(analyzerHost + "/api/control");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(timeout * 1000);
            connection.setDoOutput(true);
 
            JSONObject requestData = new JSONObject();
            requestData.put("code", code);
 
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestData.toString().getBytes());
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
 
                JSONObject responseJson = new JSONObject(response.toString());
                msg = responseJson.getString("msg");
                if (responseJson.getInt("code") == 1000) {
                    control = responseJson.optJSONObject("control");
                    state = true;
                }
            } else {
                msg = "status_code=" + responseCode;
            }
 
            connection.disconnect();
            analyzerServerState = true;
        } catch (Exception e) {
            analyzerServerState = false;
            msg = e.toString();
        }
 
        Map<String,Object> map=new HashMap<>();
        map.put("state", state);
        map.put("msg", msg);
        map.put("data", control);
        return map;
    }
    */
/**
     * 控制添加操作
     *
     * @param code 设备代码
     * @param algorithmCode 算法代码
     * @param objects 识别目标参数
     * @param objectCode 预警目标代码
     * @param minInterval 最小间隔时间
     * @param classThresh 分类阈值
     * @param overlapThresh 重叠阈值
     * @param streamUrl 流媒体URL
     * @param pushStream 是否推送流,1表示推送,0表示不推送
     * @param pushStreamUrl 推送流媒体URL
     * @return 包含操作结果的状态码和消息信息的Map对象
     *//*
 
 
    public Map<String,Object> controlAdd(String code, String algorithmCode,String objects, String objectCode, Long minInterval, double classThresh, double overlapThresh, String streamUrl,Long pushStream, String pushStreamUrl) {
        int state_code = 500;
        String msg = "error";
 
        try {
            URL url = new URL(analyzerHost + "/api/control/add");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(timeout * 1000);
            connection.setDoOutput(true);
 
            JSONObject requestData = new JSONObject();
            requestData.put("code", code);
            requestData.put("objects", objects);
            requestData.put("algorithmCode", algorithmCode);
            requestData.put("objectCode", objectCode);
            requestData.put("minInterval", Long.toString(minInterval));
            requestData.put("classThresh", Double.toString(classThresh));
            requestData.put("overlapThresh", Double.toString(overlapThresh));
            requestData.put("streamUrl", streamUrl);
            requestData.put("pushStream", pushStream==1);
            requestData.put("pushStreamUrl", pushStreamUrl);
 
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestData.toString().getBytes());
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
 
                JSONObject responseJson = new JSONObject(response.toString());
                msg = responseJson.getString("msg");
                if (responseJson.getInt("code") == 1000) {
                    state_code = 200;
                }
            } else {
                msg = "state_code=" + responseCode;
            }
 
            connection.disconnect();
            analyzerServerState = true;
        } catch (Exception e) {
            e.printStackTrace();
            analyzerServerState = false;
            msg = "视频分析器未启动,请启动!";
        }
 
        Map<String,Object> map=new HashMap<>();
        map.put("code", state_code);
        map.put("msg", msg);
        return map;
    }
 
    public Map<String,Object> controlCancel(String code) {
        int state_code = 500;
        String msg = "error";
 
        try {
            URL url = new URL(analyzerHost + "/api/control/cancel");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(timeout * 1000);
            connection.setDoOutput(true);
 
            JSONObject requestData = new JSONObject();
            requestData.put("code", code);
 
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestData.toString().getBytes());
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
 
                JSONObject responseJson = new JSONObject(response.toString());
                msg = responseJson.getString("msg");
                if (responseJson.getInt("code") == 1000) {
                    state_code = 200;
                }
            } else {
                msg = "status_code=" + responseCode;
            }
 
            connection.disconnect();
            analyzerServerState = true;
        } catch (Exception e) {
            analyzerServerState = false;
            msg = "视频分析器未启动,请启动!";
        }
 
        Map<String,Object> map=new HashMap<>();
        map.put("code", state_code);
        map.put("msg", msg);
        return map;
    }
}*/
package com.ruoyi.business.aidetection.config;
 
import com.ruoyi.business.aidetection.domain.vo.AvControlAddVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
@Component
@Data
@Slf4j
@DependsOn("readConfig")
 
public class Analyzer {
 
    private static final String API_CONTROLS = "/api/controls";
    private static final String API_CONTROL = "/api/control";
    private static final String API_CONTROL_ADD = "/api/control/add";
    private static final String API_CONTROL_CANCEL = "/api/control/cancel";
 
    @Autowired
    private ReadConfig readConfig;
 
    private String analyzerHost;
    private int timeout = 1;
    private boolean analyzerServerState = false;
 
    public Analyzer(ReadConfig readConfig) {
        this.readConfig = readConfig;
        this.analyzerHost = readConfig.getAnalyzerHost();
    }
 
    /**
     * 获取所有控制信息
     */
    public Map<String, Object> controls() {
        return sendRequest(API_CONTROLS, createSafeJson().toString(), "controls");
    }
 
    /**
     * 获取单个控制信息
     */
    public Map<String, Object> control(String code) {
        JSONObject requestData = createSafeJson("code", code);
        if (requestData == null) {
            return createErrorResponse("Failed to create JSON for control request");
        }
        return sendRequest(API_CONTROL, requestData.toString(), "control");
    }
 
    /**
     * 添加控制信息
     */
    public Map<String, Object> controlAdd(AvControlAddVo avControlAddVo) {
 
        JSONObject requestData = createSafeJson();
        try {
            requestData.put("code", avControlAddVo.getCode());
            requestData.put("objects", avControlAddVo.getObjects());
            requestData.put("algorithmCode", avControlAddVo.getAlgorithmCode());
            requestData.put("alarmObject", avControlAddVo.getObjectCode());
            requestData.put("modelCode", avControlAddVo.getModelCode());
            requestData.put("minInterval", avControlAddVo.getMinInterval());
            requestData.put("classThresh", avControlAddVo.getClassThresh());
            requestData.put("overlapThresh", avControlAddVo.getOverlapThresh());
            requestData.put("streamUrl", avControlAddVo.getStreamUrl());
            requestData.put("pushStream", avControlAddVo.getPushStream() == 1L);
            requestData.put("recognitionRegion", avControlAddVo.getRecognitionRegion());//算法识别区域坐标点 x1, y1, x2, y2, x3, y3, x4, y4
            requestData.put("pushStreamUrl", avControlAddVo.getPushStreamUrl());
        } catch (Exception e) {
            log.error("Error creating JSON for controlAdd: {}", e.getMessage(), e);
            return createErrorResponse("Failed to create JSON for controlAdd request");
        }
 
        return sendRequest(API_CONTROL_ADD, requestData.toString(), "controlAdd");
    }
 
    /**
     * 取消控制
     */
    public Map<String, Object> controlCancel(String code) {
        JSONObject requestData = createSafeJson("code", code);
        if (requestData == null) {
            return createErrorResponse("Failed to create JSON for controlCancel request");
        }
        return sendRequest(API_CONTROL_CANCEL, requestData.toString(), "controlCancel");
    }
 
    /**
     * 通用发送 HTTP 请求方法
     */
    private Map<String, Object> sendRequest(String apiEndpoint, String requestData, String action) {
        String code = "500";
        String msg = "Error occurred";
        Object data = null;
 
        try {
            // 构建 URL 和连接
            URL url = new URL(analyzerHost + apiEndpoint);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(timeout * 1000);
            connection.setDoOutput(true);
 
            // 发送请求
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestData.getBytes());
                outputStream.flush();
            }
 
            // 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    StringBuilder responseBuilder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        responseBuilder.append(line);
                    }
                    JSONObject responseJson = new JSONObject(responseBuilder.toString());
                    msg = responseJson.optString("msg", "No message");
 
                    if (responseJson.optInt("code", -1) == 1000) {
                        code = "200";
                        data = responseJson.opt("data");
                    }
                }
            } else {
                msg = "HTTP Error: status_code=" + responseCode;
                log.warn("{} request failed with status code: {}", action, responseCode);
            }
 
            connection.disconnect();
            analyzerServerState = true;
        } catch (Exception e) {
            analyzerServerState = false;
            msg = "Analyzer server is not running or request failed!";
            log.error("{} request failed: {}", action, e.getMessage(), e);
        }
 
        // 构建结果
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }
 
    /**
     * 安全创建 JSON 对象
     */
    private JSONObject createSafeJson() {
        try {
            return new JSONObject();
        } catch (Exception e) {
            log.error("Error creating empty JSON object: {}", e.getMessage(), e);
            return null;
        }
    }
 
    /**
     * 安全创建带参数的 JSON 对象
     */
    private JSONObject createSafeJson(String key, Object value) {
        try {
            return new JSONObject().put(key, value);
        } catch (Exception e) {
            log.error("Error creating JSON object with key: {}, value: {}, error: {}", key, value, e.getMessage(), e);
            return null;
        }
    }
 
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("code", "500");
        errorResponse.put("msg", message);
        errorResponse.put("data", null);
        return errorResponse;
    }
}