jiangping
2024-12-13 77cb365302cc814df041e31e4a880d804a93383f
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
package com.doumee.core.haikang.service;
 
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.TypeReference;
    import com.doumee.core.haikang.model.HKConstants;
    import com.doumee.core.haikang.model.cars.BaseCarsPageResponse;
    import com.doumee.core.haikang.model.cars.BaseCarsResponse;
    import com.doumee.core.haikang.model.cars.request.CarsAlarmListRequest;
    import com.doumee.core.haikang.model.cars.request.CarsDeviceRequest;
    import com.doumee.core.haikang.model.cars.request.CarsGpsRequest;
    import com.doumee.core.haikang.model.cars.response.*;
    import com.doumee.core.haikang.model.param.BaseListPageResponse;
    import com.doumee.core.haikang.model.param.BaseResponse;
    import com.doumee.core.haikang.model.param.respose.FindHomeAlarmInfoPageResponse;
    import com.doumee.core.utils.Constants;
    import com.doumee.core.utils.DateUtil;
    import com.google.common.collect.Maps;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    import org.springframework.http.HttpMethod;
 
    import java.io.UnsupportedEncodingException;
    import java.util.*;
 
public class HKCarOpenService {
 
    public static   String ACCESS_KEY = "D_SUB_gfJkiUxt_1723101405213";
    public static   String ACCESS_SECRET = "0vB3VLU21SC6eG8T";
    private static final String SIGNATURE_METHOD = "HMAC-SHA1";
    private static final String DEFAULT_CHARSET  = "UTF-8";
    private static final String REGION_ID = "cn-hangzhou";
    private static final String VERSION = "2.1.0";
    public static   String BASE_URL = "https://open.hikvisionauto.com:14021/v2/";
    private static TreeMap<String, String> getBaseParams()   {
        Map<String, String> params = Maps.newHashMap();
        params.put("SignatureMethod", SIGNATURE_METHOD);
        params.put("SignatureNonce", UUID.randomUUID().toString());
        params.put("AccessKey", ACCESS_KEY);
        params.put("Timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("Version", VERSION);
        params.put("RegionId", REGION_ID);
        TreeMap<String, String> sortParas = Maps.newTreeMap();
        sortParas.putAll(params);
        return sortParas;
    }
 
    public static String sign(String accessSecret, TreeMap<String, String> params, HttpMethod method) throws Exception {
        String stringToSign = getStringToSign(params, method);
        System.out.println("StringToSign = [" + stringToSign + "]");
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes(DEFAULT_CHARSET), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(DEFAULT_CHARSET));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
 
    private static String getStringToSign(TreeMap<String, String> params, HttpMethod method) throws Exception {
        StringBuilder sortQueryStringTmp = new StringBuilder();
        for(Map.Entry<String, String> entry : params.entrySet()){
            sortQueryStringTmp.append("&").append(specialUrlEncode(entry.getKey())).append("=").append(specialUrlEncode(entry.getValue()));
        }
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(method.toString()).append("&").append(specialUrlEncode("/")).append("&").append(specialUrlEncode(sortQueryStringTmp.substring(1)));
        return stringToSign.toString();
    }
 
    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
 
    public static void main(String[] args) {
        getAllCarsDetais();
    }
 
    public static List<CarsDeviceDetaisResponse> getAllCarsDetais() {
        List<CarsDeviceDetaisResponse> list = new ArrayList<>();
        BaseCarsPageResponse<CarsDeviceResponse>  data = getDeviceList(new CarsDeviceRequest());
        if(data!=null &&data.getResults()!=null){
            List<String> cars = new ArrayList<>();
            List<String> codes = new ArrayList<>();
            for(CarsDeviceResponse model :data.getResults()){
//                System.out.println("=================车牌号:"+model.getPlateNum());
                cars.add(model.getPlateNum());
                codes.add(model.getTerminalID());
                CarsDeviceDetaisResponse t = new CarsDeviceDetaisResponse();
                t.setPlateNum(model.getPlateNum());
                t.setTerminalID(model.getTerminalID());
                /*CarsGpsRequest gp = new CarsGpsRequest();
                gp.setDeviceCode(t.getTerminalID());
                gp.setFilterSupplementGps(false);
                gp.setFilterSupplementGps(false);
                gp.setStartTime(DateUtil.getYesterday()+" 00:00:00");
                gp.setEndTime(DateUtil.getNowPlusTime());
                gp.setPageNo(1);
                gp.setPageSize(10);*/
                 CarsGpsResponse tg = getLatestGpsInfo(t.getTerminalID());
                if(tg!=null ){
                    t.setSpeed(tg.getSpeed());
                    t.setLatitude(tg.getLatitude());
                    t.setLongitude(tg.getLongitude());
                    t.setCollectTime(tg.getCollectTime());
                    t.setAccStatus(tg.getAccStatus());
                    t.setGpsValid(tg.getGpsValid());
                }
                list.add(t);
            }
            System.out.println("=================车牌总数:"+codes.size());
            Map<String,Integer>   statusList = getDeviceStatusList(codes);
            if(statusList!=null &&statusList.size()>0){
                for(Map.Entry<String, Integer> entry : statusList.entrySet()){
                    CarsDeviceDetaisResponse t = getFromListById(entry.getKey(),list);
                    if(t!=null) {
                        t.setStatus(entry.getValue());
                    }
                }
            }
        }
        for(CarsDeviceDetaisResponse m  : list){
 
            System.out.println("=================车牌号:"+m.getPlateNum()+" 状态:【"+m.getStatus()+"】"+" 位置:【"+m.getLongitude()+","+m.getLatitude()+"】");
        }
        return list;
    }
    public static List<CarsAlarmResultListResponse> getAlarmEvemtList(List<CarsDeviceDetaisResponse> detaisResponses ,  Date date) {
        List<CarsAlarmResultListResponse> list = new ArrayList<>();
        if(detaisResponses ==null || detaisResponses.size()==0){
            return list ;
        }
        CarsAlarmListRequest param = new CarsAlarmListRequest();
        param.setStartTime(DateUtil.getPlusTime2(DateUtil.getStartOfDay(date)));
        param.setEndTime(DateUtil.getPlusTime2(DateUtil.getEndOfDay(date)));
        param.setPageNo(1);
        param.setPageSize(100);
        for( CarsDeviceDetaisResponse de :detaisResponses ){
            param.setDeviceCode(de.getTerminalID());
            BaseCarsPageResponse<CarsAlarmListResponse>  data = getAlarmList(param);
            if(data!=null &&data.getResults()!=null){
                for(CarsAlarmListResponse model :data.getResults()){
                    CarsAlarmResultListResponse tm = new CarsAlarmResultListResponse();
                    tm.setTime(model.getTime());
                    tm.setCarCode(de.getPlateNum());
                    tm.setType(model.getType());
                    tm.setSubType(model.getSubType());
                    Date tmDate = DateUtil.fromStringToDate("yyyy-MM-dd HH:mm:ss", tm.getTime() );
                    if(tmDate!=null){
                        tm.setTimeStamp(tmDate.getTime());
                    }
                    tm.setTitle(HKConstants.CarsEventType.getName(tm.getType(),tm.getSubType()));
                    list.add(tm);
                }
            }
        }
        Collections.sort(list, (o1, o2) -> {
            return (int) (o1.getTimeStamp() - o2.getTimeStamp()); //按数量从大到小排序
        });
        return list;
    }
 
    private static CarsDeviceDetaisResponse getFromListById(String key, List<CarsDeviceDetaisResponse> list) {
        for(CarsDeviceDetaisResponse dd  :list){
            if(dd.getTerminalID()!=null && key !=null && dd.getTerminalID().equals(key)){
                return  dd;
            }
        }
        return null;
    }
 
    public static String sendRequest(String url,TreeMap<String, String> map){
        try {
            StringBuilder sortQueryStringTmp = new StringBuilder();
            for(Map.Entry<String, String> entry : map.entrySet()){
                sortQueryStringTmp
                        .append("&")
                        .append(specialUrlEncode(entry.getKey()))
                        .append("=")
                        .append(specialUrlEncode(entry.getValue()));
            }
            //与下方的HttpGet对应,采用的是HttpMethod.GET
            String sign = sign(ACCESS_SECRET + "&", map, HttpMethod.GET);
            url += "?Signature=" + specialUrlEncode(sign) + sortQueryStringTmp.toString();
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            //与上方的HttpMethod.GET对应,使用HttpGet
            HttpGet httpDelete = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpDelete);
            return  EntityUtils.toString(response.getEntity());
        }catch (Exception e){
            e.printStackTrace();
        }
 
        return null;
}
    public static  BaseCarsPageResponse<CarsGpsResponse>  getGpsList(CarsGpsRequest param)   {
        String url = BASE_URL + "gps/list/";
        TreeMap<String, String> BASE_PARAMS = getBaseParams();
        if(StringUtils.isNotBlank(param.getEndTime())) {
            BASE_PARAMS.put("endTime", param.getEndTime());
        }
        if(StringUtils.isNotBlank(param.getStartTime())){
             BASE_PARAMS.put("startTime",param.getStartTime());
        }
        if( param.getFilterInvalidGps() !=null && !param.getFilterInvalidGps()){
             BASE_PARAMS.put("filterInvalidGps", "false");
        }
        if( param.getFilterSupplementGps() !=null && !param.getFilterSupplementGps()){
             BASE_PARAMS.put("filterSupplementGps", "false");
        }
        if(StringUtils.isNotBlank(param.getDeviceCode())){
            BASE_PARAMS.put("deviceCode", param.getDeviceCode().toString());//设备型号秘钥
        }
        BASE_PARAMS.put("pageSize",Constants.equalsInteger(param.getPageSize(),0)? "100":param.getPageSize().toString());//页面大小
        BASE_PARAMS.put("pageNo", Constants.equalsInteger(param.getPageNo(),0)? "1":param.getPageNo().toString());//当前页
        String str = sendRequest(url,BASE_PARAMS);
        TypeReference typeReference =
                new TypeReference<BaseCarsResponse<BaseCarsPageResponse<CarsGpsResponse>>>(){};
        BaseCarsResponse<BaseCarsPageResponse<CarsGpsResponse>>   result = JSONObject.parseObject(str, typeReference.getType());
        if(result!=null && Constants.equalsInteger(result.getStatus(),0)){
            return  result.getData();
        }
        return  null;
    }
    public static  CarsGpsResponse   getLatestGpsInfo(String deviceCode)   {
        String url = BASE_URL + "gps/latest/";
        TreeMap<String, String> BASE_PARAMS = getBaseParams();
        BASE_PARAMS.put("deviceCode", deviceCode);//设备型号秘钥
        String str = sendRequest(url,BASE_PARAMS);
        TypeReference typeReference =
                new TypeReference<BaseCarsResponse<CarsGpsResponse>>(){};
        BaseCarsResponse<CarsGpsResponse>   result = JSONObject.parseObject(str, typeReference.getType());
        if(result!=null && Constants.equalsInteger(result.getStatus(),0)){
            return  result.getData();
        }
        return  null;
    }
    public static   Map<String,Integer>   getDeviceStatusList(List<String> code)   {
        String url = BASE_URL + "device/status/";
        TreeMap<String, String> BASE_PARAMS = getBaseParams();
        if(code ==null || code.size() ==0){
            return  new HashMap<>();
        }
        BASE_PARAMS.put("deviceCodeList", JSONObject.toJSONString(code));//终端手机号列表
        String str = sendRequest(url,BASE_PARAMS);
        TypeReference typeReference =
                new TypeReference<BaseCarsResponse<Map<String,Integer>>>(){};
        BaseCarsResponse<Map<String,Integer>>   result = JSONObject.parseObject(str, typeReference.getType());
        if(result!=null && Constants.equalsInteger(result.getStatus(),0)){
            return  result.getData();
        }
        return  null;
    }
    public static BaseCarsPageResponse<CarsDeviceResponse> getDeviceList(CarsDeviceRequest param)  {
        String url = BASE_URL + "device/list/";
        TreeMap<String, String> BASE_PARAMS = getBaseParams();
        if(StringUtils.isNotBlank(param.getProductKey())){
            BASE_PARAMS.put("productKey", param.getProductKey());//设备型号秘钥
        }
        BASE_PARAMS.put("pageSize",Constants.equalsInteger(param.getPageSize(),0)? "100":param.getPageSize().toString());//页面大小
        BASE_PARAMS.put("pageNo", Constants.equalsInteger(param.getPageNo(),0)? "1":param.getPageNo().toString());//当前页
        String str = sendRequest(url,BASE_PARAMS);
        TypeReference typeReference =
                new TypeReference<BaseCarsResponse<BaseCarsPageResponse<CarsDeviceResponse>>>(){};
        BaseCarsResponse<BaseCarsPageResponse<CarsDeviceResponse>>   result = JSONObject.parseObject(str, typeReference.getType());
        if(result!=null && Constants.equalsInteger(result.getStatus(),0)){
            return  result.getData();
        }
        return  null;
    }
    public static BaseCarsPageResponse<CarsAlarmListResponse> getAlarmList(CarsAlarmListRequest param)  {
        String url = BASE_URL + "alarm/list/";
        TreeMap<String, String> BASE_PARAMS = getBaseParams();
        if(StringUtils.isNotBlank(param.getStartTime())){
            BASE_PARAMS.put("startTime", param.getStartTime());
        }
        if(StringUtils.isNotBlank(param.getEndTime())){
            BASE_PARAMS.put("endTime", param.getEndTime());
        }
        BASE_PARAMS.put("deviceCode", param.getDeviceCode());
        BASE_PARAMS.put("pageSize",Constants.equalsInteger(param.getPageSize(),0)? "100":param.getPageSize().toString());//页面大小
        BASE_PARAMS.put("pageNo", Constants.equalsInteger(param.getPageNo(),0)? "1":param.getPageNo().toString());//当前页
        String str = sendRequest(url,BASE_PARAMS);
        TypeReference typeReference =
                new TypeReference<BaseCarsResponse<BaseCarsPageResponse<CarsAlarmListResponse>>>(){};
        BaseCarsResponse<BaseCarsPageResponse<CarsAlarmListResponse>>   result = JSONObject.parseObject(str, typeReference.getType());
        if(result!=null && Constants.equalsInteger(result.getStatus(),0)){
            return  result.getData();
        }
        return  null;
    }
}