Commit 4471c56e by yanHeng

[初始化] wuLink对接

parent 0e8cec42
......@@ -4,6 +4,8 @@ import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
public class HttpSendUtil {
......@@ -54,6 +56,56 @@ public class HttpSendUtil {
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param,String token) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("Authorization","Bearer " +token);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
// result=new String(result.getBytes(),"utf-8");
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
......@@ -161,5 +213,4 @@ public class HttpSendUtil {
}
return result.toString();
}
}
package com.beecode.inz.common.util;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Description:IOT平台对接工具类
*
* @author 孟庆鑫
* @version 1.0
* @date: 2021/7/13 15:06
*/
@Component
public class IotPlatformUtils {
private static Logger logger = LoggerFactory.getLogger(IotPlatformUtils.class);
private RestTemplate restTemplate;
public static String getGpsWuLingTokenRedisKey(String clietId, String clientSecret) {
return "gps_wu_link_token_key" + clietId + "_" + clientSecret;
}
public static String getGpsWuLingImeisTrackingRedisKey(String imeis) {
return "gpsoo_imeis_tracking_key" + "_"+imeis;
}
//获取token必填参数 如下三个
private static final String GRANT_TYPE = "client_credentials";
private static final String CLIET_ID = "jt808";
private static final String CLIENT_SECRET = "f04dd1e4";
//获取token
private static final String GPS_WU_LING_DOMAIN = "http://dev.kunlun.cloud/";
//获取设备
private static final String GPS_WU_LING_DOMAIN_API = "http://iot.dev.kunlun.cloud/";
/**
* 获取tokenUrl
*/
private static final String TOKEN_URL = GPS_WU_LING_DOMAIN +"iot/oauth/token";
/**
* 根据设备序列号获取id
*/
private static final String FIND_GATEWAY_ID_URL = GPS_WU_LING_DOMAIN +"iot/gateway/api/findGatewayId";
/**
* 历史轨迹URL
*/
private static final String HISTORY_URL = GPS_WU_LING_DOMAIN +"devices/history";
//跟踪url
private static final String TRACKING_URL = GPS_WU_LING_DOMAIN_API +"api/v1/gateways/【%1$s】/metrics/last";
/**
* 获取单个设备最新数据
* @Author yanHeng
* @Date 2022/4/25 11:28
* @Param [imei]
* @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
**/
public static List<Map<String, Object>> tracking(String imeis) throws Exception{
if(StringUtils.isEmpty(imeis)){
return null;
}
String token = "";
HashMap<String, Object> tokenMap = getAuthToken(CLIET_ID, CLIENT_SECRET);
if ((int) tokenMap.get("status") == -1 || (int) tokenMap.get("status") == -2) {
token = tokenMap.get("data").toString();
}
if(token==null || "".equals(token)){
return null;
}
List<Map<String,Object>> imeisInfos = new ArrayList<>();
List<String> imeisInfoKey = new ArrayList<>();
String[] split = imeis.split(",");
for (String s : split) {
String s1 = RedisUtils.getInstance().get(getGpsWuLingImeisTrackingRedisKey(imeis));
if(StringUtils.isNotEmpty(s1)){
imeisInfos.add(new JSONObject(s1).toMap());
}else {
imeisInfoKey.add(s);
}
}
String param = "serialNumber=" + imeisInfoKey.get(0);
//根据设备序号 查询网关id
String findGatewayId = HttpSendUtil.sendGet(FIND_GATEWAY_ID_URL,param ,token);
JSONObject findStr = new JSONObject(findGatewayId);
int findCode = findStr.getInt("code");
String id = "";
if (20000==(findCode)) {
id = findStr.getJSONObject("data").toString();
}
if("".equals(id)){
return null;
}
//根据网关id 查询网关最新数据
String sendGet = HttpSendUtil.sendGet(String.format(TRACKING_URL,id), null,token);
JSONObject getStr = new JSONObject(sendGet);
int code = getStr.getInt("code");
if (20000==(code)) {
JSONArray data = getStr.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
//每分钟限制了600次请求 8秒缓存,可能不大够..
JSONObject jsonObject = data.getJSONObject(i);
Map<String,Object> imeisInfo = jsonObject.toMap();
RedisUtils.getInstance().set(getGpsWuLingImeisTrackingRedisKey(imeis), jsonObject.toString(),8);
imeisInfos.add(imeisInfo);
}
}else {
logger.error("请求GPSWuLink平台获取tracking出错,错误信息"+getStr.get("msg")+",设备号列表"+imeis);
}
return imeisInfos;
}
/**
* Description:获取平台accesstoken
*
* @author yanHeng
* @date 2022-04-25
* @return: 0:请求正常 -1:clientId或clientSecret为空 -2:请求accessToken服务器异常
*/
public static HashMap<String, Object> getAuthToken(String clientId, String clientSecret)throws Exception {
HashMap<String, Object> map = new HashMap<>();
if (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) {
//clientId和clientSecret不能为空
map.put("status", -1);
map.put("message", "当前项目未注册IOT平台");
return map;
}
String accessTokenData = null;
try {
accessTokenData = RedisUtils.getInstance().get(getGpsWuLingTokenRedisKey(CLIET_ID, CLIENT_SECRET));
} catch (Exception e) {
e.printStackTrace();
}
//优先从redis缓存拿
if (StringUtils.isNotBlank(accessTokenData)) {
map.put("status", 0);
map.put("data", accessTokenData);
return map;
}
String sendParam = "grant_type="+GRANT_TYPE + "&client_id=" + CLIET_ID + "&client_secret=" + CLIENT_SECRET;
String sendPost = HttpSendUtil.sendPost(TOKEN_URL, sendParam, StandardCharsets.UTF_8.name());
JSONObject postStr = new JSONObject(sendPost);
String accessToken = postStr.getString("access_token");
if (accessToken != null) {
RedisUtils.getInstance().set(getGpsWuLingTokenRedisKey(CLIET_ID, CLIENT_SECRET),accessToken,postStr.getInt("expires_in")-3);
map.put("status", 0);
map.put("data", accessToken);
return map;
} else {
//获取accesstoken异常
map.put("status", -2);
map.put("message", "IOT平台返回错误");
return map;
}
}
}
......@@ -4,11 +4,11 @@ import com.beecode.bap.attachment.common.Page;
import com.beecode.bcp.type.KObject;
import com.beecode.inz.common.BaseConstants;
import com.beecode.inz.common.util.GpsOOUtil;
import com.beecode.inz.common.util.IotPlatformUtils;
import com.xyst.dinas.biz.dao.ShipInfoDao;
import com.xyst.dinas.biz.service.ShipInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
......@@ -73,24 +73,51 @@ public class ShipInfoServiceImpl implements ShipInfoService {
return shipInfoDao.getAllShipByRegionalCompanyIds(uuidList);
}
//旧版 对接代码 谷米平台
// @Override
// public List<Map<String, Object>> getShipsTracking(List<KObject> allShipByRegionalCompanyIds) throws Exception {
// List<Map<String, Object>> list = new ArrayList<>();
// Map<String, Object> stringObjectHashMap;
// for (KObject allShipByRegionalCompanyId : allShipByRegionalCompanyIds) {
// String account = allShipByRegionalCompanyId.getString("account");
// String accountPassword = allShipByRegionalCompanyId.getString("accountPassword");
// String imei = allShipByRegionalCompanyId.getString("deviceNumber");
//
// stringObjectHashMap = new HashMap<>();
// stringObjectHashMap.put("shipInfo",allShipByRegionalCompanyId);
// stringObjectHashMap.put("shipInfoId",allShipByRegionalCompanyId.getUuid(BaseConstants.ID));
//
// if(StringUtils.isEmpty(account)||StringUtils.isEmpty(accountPassword)||StringUtils.isEmpty(imei)){
// stringObjectHashMap.put("trackingInfo",new ArrayList<>());
// continue;
// }
// List<Map<String,Object>> tracking = GpsOOUtil.tracking(account, accountPassword, imei, null);
// stringObjectHashMap.put("trackingInfo",tracking);
//
// list.add(stringObjectHashMap);
// }
// return list;
// }
@Override
public List<Map<String, Object>> getShipsTracking(List<KObject> allShipByRegionalCompanyIds) throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> stringObjectHashMap;
for (KObject allShipByRegionalCompanyId : allShipByRegionalCompanyIds) {
String account = allShipByRegionalCompanyId.getString("account");
String accountPassword = allShipByRegionalCompanyId.getString("accountPassword");
String imei = allShipByRegionalCompanyId.getString("deviceNumber");
stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("shipInfo",allShipByRegionalCompanyId);
stringObjectHashMap.put("shipInfoId",allShipByRegionalCompanyId.getUuid(BaseConstants.ID));
if(StringUtils.isEmpty(account)||StringUtils.isEmpty(accountPassword)||StringUtils.isEmpty(imei)){
if(StringUtils.isEmpty(imei)){
stringObjectHashMap.put("trackingInfo",new ArrayList<>());
continue;
}
List<Map<String,Object>> tracking = GpsOOUtil.tracking(account, accountPassword, imei, null);
List<Map<String,Object>> tracking = IotPlatformUtils.tracking(imei);
stringObjectHashMap.put("trackingInfo",tracking);
list.add(stringObjectHashMap);
......
package com.xyst.dinas.camera.constant;
import com.beecode.inz.common.util.HttpSendUtil;
import com.beecode.inz.common.util.RedisUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
/**
* Description:IOT平台对接工具类
*
* @author 孟庆鑫
* @version 1.0
* @date: 2021/7/13 15:06
*/
@Component
public class IotPlatformUtils {
public static String getGpsWuLingTokenRedisKey(String clietId, String clientSecret) {
return "gps_wu_link_token_key" + clietId + "_" + clientSecret;
}
//获取token必填参数 如下三个
private static final String GRANT_TYPE = "client_credentials";
private static final String CLIET_ID = "jt808";
private static final String CLIENT_SECRET = "f04dd1e4";
private static final String GPS_WU_LING_DOMAIN = "http://dev.kunlun.cloud/iot/";
/**
* 获取tokenUrl
*/
private static final String TOKEN_URL = GPS_WU_LING_DOMAIN +"oauth/token";
/**
* 根据设备序列号获取id
*/
private static final String FIND_GATEWAY_ID_URL = GPS_WU_LING_DOMAIN +"gateway/api/findGatewayId";
/**
* 根据设备id查询⽹关指标信息
*/
private static final String GATEWAYINDICATORS_URL = GPS_WU_LING_DOMAIN +"gateway/api/gatewayIndicators";
/**
* 历史轨迹URL
*/
private static final String HISTORY_URL = GPS_WU_LING_DOMAIN +"devices/history";
/**
* Description:获取平台accesstoken
*
* @author 孟庆鑫
* @date 2021/7/13 16:45
* @return: 0:请求正常 -1:clientId或clientSecret为空 -2:请求accessToken服务器异常
*/
public HashMap<String, Object> getAuthToken(String clientId, String clientSecret)throws Exception {
HashMap<String, Object> map = new HashMap<>();
if (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) {
//clientId和clientSecret不能为空
map.put("status", -1);
map.put("message", "当前项目未注册IOT平台");
return map;
}
String accessTokenData = null;
try {
accessTokenData = RedisUtils.getInstance().get(getGpsWuLingTokenRedisKey(CLIET_ID, CLIENT_SECRET));
} catch (Exception e) {
e.printStackTrace();
}
//优先从redis缓存拿
if (StringUtils.isNotBlank(accessTokenData)) {
map.put("status", 0);
map.put("data", accessTokenData);
return map;
}
String sendParam = "grant_type="+GRANT_TYPE + "&client_id=" + CLIET_ID + "&client_secret=" + CLIENT_SECRET;
String sendPost = HttpSendUtil.sendPost(TOKEN_URL, sendParam, StandardCharsets.UTF_8.name());
JSONObject postStr = new JSONObject(sendPost);
String accessToken = postStr.getString("access_token");
if (accessToken != null) {
RedisUtils.getInstance().set(getGpsWuLingTokenRedisKey(CLIET_ID, CLIENT_SECRET),accessToken,postStr.getInt("expires_in")-3);
map.put("status", 0);
map.put("data", accessToken);
return map;
} else {
//获取accesstoken异常
map.put("status", -2);
map.put("message", "IOT平台返回错误");
return map;
}
}
}
......@@ -2,7 +2,7 @@ package com.xyst.dinas.camera.web;
import com.beecode.inz.basis.team.pojo.ResponseObj;
import com.xyst.dinas.camera.constant.IotPlatformUtils;
import com.beecode.inz.common.util.IotPlatformUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
......@@ -39,7 +39,7 @@ public class IotPlatformController {
@GetMapping("/getAccessToken")
public ResponseObj getAccessToken() throws Exception{
HashMap<String, Object> tokenMap = iotPlatformUtils.getAuthToken(CLIET_ID, CLIENT_SECRET);
HashMap<String, Object> tokenMap = IotPlatformUtils.getAuthToken(CLIET_ID, CLIENT_SECRET);
if ((int) tokenMap.get("status") == -1 || (int) tokenMap.get("status") == -2) {
return ResponseObj.success("获取失败",tokenMap.get("message").toString());
} else {
......
package com.xyst.dinas.camera.websocket;
import com.beecode.amino.core.Amino;
import com.xyst.dinas.camera.web.IotPlatformController;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
/**
* @author 孟庆鑫
* @title: WsClient
* @projectName demo
* @description: webSocket
* @date 2021/8/3017:12
*/
public class WsClient extends WebSocketClient {
private static final Logger logger = LoggerFactory.getLogger(WsClient.class);
//根据这个状态去查询预警设置表
private static final Integer status = 1;
//创建 SingleObject 的一个对象
private static WsClient instance;
private static String serverUri = "";
private static String url = "ws://172.17.74.106:9001/ws?";
//private static String url = "ws://192.168.1.3:9001/ws?";
static {
try {
IotPlatformController iotPlatformController = Amino.getApplicationContext().getBean(IotPlatformController.class);
String accessToken = (String) iotPlatformController.getAccessToken().getData();
// EquipmentController equipmentController = Amino.getApplicationContext().getBean(EquipmentController.class);
// ResultMoudel resultMoudel = equipmentController.queryEquipmentAll(new Equipment());
// List<Equipment> equipments = (List<Equipment>) resultMoudel.getBody();
String equipmentId = "";
// for (Equipment equipment : equipments) {
// if (!ObjectUtils.isEmpty(equipment.getEquipmentId())) {
// if (!equipmentId.contains(equipment.getEquipmentId() + ",")) {
// equipmentId = equipmentId + equipment.getEquipmentId() + ",";
// }
// }
// }
url = url + "token=" + accessToken + "&gateway=" + equipmentId.substring(0, equipmentId.length() - 1);
serverUri = url;
instance = new WsClient(serverUri);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setUrl(String url) throws URISyntaxException {
WsClient.serverUri = url;
instance = new WsClient(url);
}
//获取唯一可用的对象
public static WsClient getInstance() throws URISyntaxException {
return instance;
}
private WsClient(String serverUri) throws URISyntaxException {
super(new URI(serverUri));
}
@Override
public void onOpen(ServerHandshake arg0) {
System.out.println("握手成功");
}
@Override
public void onMessage(String message) {
}
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
System.out.println("连接关闭");
}
@Override
public void onError(Exception arg0) {
System.out.println("发生错误" + arg0);
}
// @Override
// public void onMessage(String arg0) {
// //收到信息,转换成map
// System.out.println("收到消息" + arg0);
// JSONObject jsonMap = JSONObject.parseObject(arg0);
// Map<String, Object> map = jsonMap;
// //查询出所有的设备信息,需要所有的设备id去做预警监控
// EquipmentController equipmentController = SpringContext.getBean(EquipmentController.class);
// ResultMoudel resultMoudel = equipmentController.queryEquipmentAll(new Equipment());
// List<Equipment> equipments = (List<Equipment>) resultMoudel.getBody();
// WarningSettingsMapper warningSettingsMapper = SpringContext.getBean(WarningSettingsMapper.class);
// EquipmentDictionaryMapper equipmentDictionaryMapper = SpringContext.getBean(EquipmentDictionaryMapper.class);
//
// //遍历所有的设备id如果gatway里有跟我一样的设备id,就监控
// for (Equipment equipment : equipments) {
// //拿到设备信息里的data
// Object data = map.get("data");
// JSONObject datajson = JSONObject.parseObject(String.valueOf(data));
// Map<String, Object> dataMap = datajson;
// //如果设备里有虫情和孢子就需要保存照片
// if (Objects.equals(dataMap.get("gateway"), equipment.getEquipmentId()) && ("3".equals(equipment.getTypeId()) || "4".equals(equipment.getTypeId()))) {
// //拿到设备信息data里的params
// Object params = dataMap.get("params");
// JSONObject objectjson = JSONObject.parseObject(String.valueOf(params));
// Map<String, Object> objectMap = objectjson;
//
// if (!ObjectUtils.isEmpty(objectMap.get("image"))) {
// // 添加UUID编码,防止文件名重复
// UUID uuid = UUID.randomUUID();
// UUID uuid1 = UUID.randomUUID();
// uploadController uploadController = new uploadController();
// //孢子
// if ("3".equals(equipment.getTypeId())) {
// String image = (String) objectMap.get("image");
// uploadController.download(image, uuid.toString(), 4);
// } else {//虫情
// String image = (String) objectMap.get("image");
// String resultImage = (String) objectMap.get("result_image");
// uploadController.download(image, uuid.toString(), 3);
// uploadController.download(resultImage, uuid1.toString(), 3);
// }
// }
//
//
// }
//
// //对比id和getway是否一致,这里要保证设备id要唯一
// if (Objects.equals(dataMap.get("gateway"), equipment.getEquipmentId())) {
// //拿到设备信息data里的params
// Object params = dataMap.get("params");
// JSONObject objectjson = JSONObject.parseObject(String.valueOf(params));
// Map<String, Object> objectMap = objectjson;
// //根据设备id去查询预警设置表
// Map<String, Object> queryMap = new HashMap<>();
// queryMap.put("equipment_type_id", equipment.getTypeId());
// queryMap.put("status", status);
// List<WarningSettings> warningSettings = warningSettingsMapper.selectByMap(queryMap);
// //遍历这个结合校验所有校验
// for (WarningSettings WarningSettings : warningSettings) {
// BigDecimal dparm = (BigDecimal) objectMap.get(WarningSettings.getAlias());
// if (null != dparm && (dparm.compareTo(new BigDecimal(WarningSettings.getMaxValue())) == 1 || dparm.compareTo(new BigDecimal(WarningSettings.getMinValue())) == -1)) {
//
// //推送预警信息
// JPushUtil jPushUtil = new JPushUtil();
// String title = "预警推送";
// String content = equipment.getName() + "设备的" + WarningSettings.getDeviceParameters() + "指标出现异常!,数值:" + String.valueOf(dparm) + "请注意!";
// Map<String, String> extras = new HashMap<>();
// extras.put("areaId", String.valueOf(equipment.getAreaId()));
// extras.put("name", equipment.getName());
// extras.put(WarningSettings.getDeviceParameters(), String.valueOf(dparm));
//
// //保存预警信息
// BreakdownRecord breakdownRecord = new BreakdownRecord();
// breakdownRecord.setEquipmentInfoId(Integer.valueOf(equipment.getEquipmentId()));
// breakdownRecord.setAreaId(equipment.getAreaId());
// breakdownRecord.setFaultParameter(WarningSettings.getDeviceParameters());
// breakdownRecord.setContent(content);
// breakdownRecord.setRemindWays(WarningSettings.getRemindWays());
// breakdownRecord.setHandleWay(0);//TODO 设备故障的还没有写呢
// breakdownRecord.setStatus(status);
// BreakdownRecordMapper breakdownRecordMapper = SpringContext.getBean(BreakdownRecordMapper.class);
// breakdownRecordMapper.insert(breakdownRecord);
//
// extras.put("id", String.valueOf(breakdownRecord.getId()));
// //我们是多个人员所以要拼接一下
// String[] split = WarningSettings.getUserId().split(",");
// String alias;
// for (int i = 0; i < split.length; i++) {
// alias = "dev_" + split[i]; //上线的时候换成prod
//
// try {
// jPushUtil.sendPushObjectPlatformAllBigText(alias, title, content, extras);
// } catch (APIConnectionException e) {
// e.printStackTrace();
// } catch (APIRequestException e) {
// logger.info("调用极光推送失败!");
// }
//
// }
// logger.info("调用极光推送!");
// }
// }
// }
// }
// }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment