package com.welampiot.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.welampiot.common.BaseResult; import com.welampiot.common.DevInfoEnum; import com.welampiot.common.InterfaceResultEnum; import com.welampiot.common.LampControlTypeEnum; import com.welampiot.configuration.MqttConfig; import com.welampiot.configuration.PlcMqttConfig; import com.welampiot.configuration.WifiMqttConfig; import com.welampiot.dto.*; import com.welampiot.handle.MqttHandler; import com.welampiot.service.*; import com.welampiot.vo.DevEnumVO; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.gavaghan.geodesy.Ellipsoid; import org.gavaghan.geodesy.GeodeticCalculator; import org.gavaghan.geodesy.GeodeticCurve; import org.gavaghan.geodesy.GlobalCoordinates; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.CRC32; import java.util.zip.GZIPInputStream; @Component public class ToolUtils { //http的编码 public enum ContentTypeEnum { CONTENT_TYPE_JSON("application/json;charset=utf-8"), CONTENT_TYPE_FORM("application/x-www-form-urlencoded;charset=utf-8") ; private String contentType; ContentTypeEnum(String contentType) { this.contentType = contentType; } } //用户的权限 final static public Integer SYSTEM_ADMIN = 1; final static public Integer COMPANY_ADMIN = 2; final static public Integer COMPANY_CUSTOMER = 3; //国标摄像头播放地址 final static private String gbHost = "47.112.108.98"; // 和风天气的key final static public String WEATHER_KEY = "2dca03c7d95c442ba8fbce9d7a96db78"; private UserDTO user; @Autowired private UserService userService; @Autowired private SectionService sectionService; @Autowired private GlobalLocationService globalLocationService; @Autowired private MqttConfig mqttConfig; @Autowired private MqttHandler mqttHandler; @Autowired private LampPoleService lampPoleService; @Autowired private PlcMqttConfig plcMqttConfig; private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$"; private static final String PATTERN_PHONE = "^1[3-9]\\d{9}$"; private static final String PATTERN_EMAIL = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; @Autowired private IpInfoService ipInfoService; @Autowired private OperationLogService operationLogService; @Autowired private GbPlayService gbPlayService; @Autowired private WifiMqttConfig wifiMqttConfig; /** * 获取用户所有路段 id * @param request * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选 */ public List getSectionList(HttpServletRequest request){ String username = request.getParameter("username"); ArrayList sectionList = new ArrayList<>(); if (username == null || username.toString().length() == 0) { sectionList.add(0); return sectionList; } user = userService.findUserByUserName(username); if (user == null) { sectionList.add(0); return sectionList; } String provinceid = request.getParameter("provinceId"); provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid; String cityid = request.getParameter("cityId"); cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid; String areaid = request.getParameter("areaId"); areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid; String sectionid = request.getParameter("sectionId"); sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid; if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){ sectionList.add(sectionid); return sectionList; } String zone = user.getZoneList(); int role = user.getRole(); List maps; List globalLocationList; ArrayList areaList = new ArrayList<>(); if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){ if (areaid == null || areaid.equals("0")){ ArrayList cityList = new ArrayList<>(); if (cityid == null || cityid.equals("0")){ globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid)); if (globalLocationList.isEmpty()){ cityid = provinceid; }else { for (GlobalLocationDTO m :globalLocationList) { cityList.add(m.getId()); } } } if (cityList.isEmpty()){ globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid)); }else { globalLocationList = globalLocationService.getListByPidList(cityList); } if (globalLocationList.isEmpty()){ areaid = cityid; }else { for (GlobalLocationDTO m :globalLocationList) { areaList.add(m.getId()); } } } } if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){ if (role != 1) { return Arrays.asList(zone.split(",")); }else { return new ArrayList<>(); } }else { if (areaid == null || areaid.equals("0")){ maps = sectionService.getListByPidList(areaList); if (role != 1){ return Arrays.asList(zone.split(",")); } }else { System.out.println(areaid); int areaid2 = Integer.valueOf(areaid); maps = sectionService.getListByPid(areaid2); } } for (SectionDTO map:maps) { sectionList.add(map.getId()); } if (sectionList.isEmpty()) sectionList.add("0"); return sectionList; } public UserDTO getUser() { return user; } public UserDTO getUser(HttpServletRequest request) { String username = request.getParameter("username"); ArrayList sectionList = new ArrayList<>(); // if (user == null) {//若换了帐号,还是上次的帐号 // user = userService.findUserByUserName(username); // } user = userService.findUserByUserName(username); return user; } /** * 返回接口信息,不带数据 * @param code 状态码 * @param version 语言类型 0 中文,1 英文,2 俄语 * @return */ public BaseResult response(InterfaceResultEnum resultEnum,Integer version){ String msg; String code = resultEnum.getCode(); if (version == 0){ msg = resultEnum.getMsgCn();} else if (version == 1) { msg = resultEnum.getMsgEn(); }else { msg = resultEnum.getMsgRu(); } BaseResult objectBaseResult = new BaseResult<>(code, msg, new Object()); Logger paramLog = LoggerFactory.getLogger("param_log"); paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult)); return objectBaseResult; } /** * 返回接口信息,带数据 * @param code 状态码 * @param version 语言类型 0 中文,1 英文,2 俄语 * @param obj 返回数据内容 * @return */ public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){ String msg; String code = resultEnum.getCode(); if (version == 0){ msg = resultEnum.getMsgCn(); } else if (version == 1) { msg = resultEnum.getMsgEn(); }else { msg = resultEnum.getMsgRu(); } BaseResult objectBaseResult = new BaseResult<>(code, msg, obj); Logger paramLog = LoggerFactory.getLogger("param_log"); paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult)); return objectBaseResult; } /** * 发送mqtt指令 * @param sendTopic 发送的topic * @param cmdInfo 发送的指令内容 * @param resTopic 接收指令返回的topic * @return */ public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){ MqttClient client; String res = ""; try { try { client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence()); MqttConnectOptions options=new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(mqttConfig.getUsername()); options.setPassword(mqttConfig.getPassword().toCharArray()); options.setConnectionTimeout(mqttConfig.getTimeout()); options.setKeepAliveInterval(mqttConfig.getKeepalive()); mqttHandler.setTopic(resTopic); // 设置回调 client.setCallback(mqttHandler); // 建立连接 client.connect(options); // MqttCustomerClient.setClient(client); client.subscribe(resTopic); // 消息发布所需参数 MqttMessage message; if (cmdInfo instanceof String){ message = new MqttMessage(((String) cmdInfo).getBytes()); }else { message = new MqttMessage((byte[]) cmdInfo); } message.setQos(0); client.publish(sendTopic, message); int in = 0; while (true){ Thread.sleep(1000); if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){ res = mqttHandler.getRes(); break; } in ++; if (in > 30) break; } client.disconnect(); }catch (Exception e){ e.printStackTrace(); } }catch (Exception e){ e.printStackTrace(); } return res; } /** * 发送mqtt指令 * @param sendTopic 发送的topic * @param cmdInfo 发送的指令内容 * @param resTopic 接收指令返回的topic * @param timeout 指令超时时间 * @return */ public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){ MqttClient client; String res = ""; try { try { client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence()); MqttConnectOptions options=new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(mqttConfig.getUsername()); options.setPassword(mqttConfig.getPassword().toCharArray()); options.setConnectionTimeout(mqttConfig.getTimeout()); options.setKeepAliveInterval(mqttConfig.getKeepalive()); mqttHandler.setTopic(resTopic); // 设置回调 client.setCallback(mqttHandler); // 建立连接 client.connect(options); // MqttCustomerClient.setClient(client); client.subscribe(resTopic); // 消息发布所需参数 MqttMessage message; if (cmdInfo instanceof String){ message = new MqttMessage(((String) cmdInfo).getBytes()); }else { message = new MqttMessage((byte[]) cmdInfo); } message.setQos(0); client.publish(sendTopic, message); int in = 0; if (timeout > 0){ while (true){ Thread.sleep(1000); if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){ res = mqttHandler.getRes(); break; } in ++; if (in > timeout) break; } } client.disconnect(); }catch (Exception e){ e.printStackTrace(); } }catch (Exception e){ e.printStackTrace(); } return res; } /** * 发送plc的mqtt指令 * @param sendTopic 发送的topic * @param cmdInfo 发送的指令内容 * @param resTopic 接收指令返回的topic * @return */ public String plcSendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){ MqttClient client; String res = ""; try { try { client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence()); MqttConnectOptions options=new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(plcMqttConfig.getUsername()); options.setPassword(plcMqttConfig.getPassword().toCharArray()); options.setConnectionTimeout(plcMqttConfig.getTimeout()); options.setKeepAliveInterval(plcMqttConfig.getKeepalive()); mqttHandler.setTopic(resTopic); // 设置回调 client.setCallback(mqttHandler); // 建立连接 client.connect(options); // MqttCustomerClient.setClient(client); client.subscribe(resTopic); // 消息发布所需参数 MqttMessage message; if (cmdInfo instanceof String){ message = new MqttMessage(((String) cmdInfo).getBytes()); }else { message = new MqttMessage((byte[]) cmdInfo); } message.setQos(0); client.publish(sendTopic, message); int in = 0; while (true){ Thread.sleep(1000); if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){ res = mqttHandler.getRes(); break; } in ++; if (in > 30) break; } client.disconnect(); }catch (Exception e){ e.printStackTrace(); } }catch (Exception e){ e.printStackTrace(); } return res; } /** * 发送plc的mqtt指令 * @param sendTopic 发送的topic * @param cmdInfo 发送的指令内容 * @param resTopic 接收指令返回的topic * @param timeout 指令超时时间 * @return */ public String plcSendMqttCmd(String sendTopic,String cmdInfo, String resTopic, Integer timeout){ MqttClient client; String res = ""; try { try { client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence()); MqttConnectOptions options=new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(plcMqttConfig.getUsername()); options.setPassword(plcMqttConfig.getPassword().toCharArray()); options.setConnectionTimeout(plcMqttConfig.getTimeout()); options.setKeepAliveInterval(plcMqttConfig.getKeepalive()); mqttHandler.setTopic(resTopic); // 设置回调 client.setCallback(mqttHandler); // 建立连接 client.connect(options); // MqttCustomerClient.setClient(client); client.subscribe(resTopic); // 消息发布所需参数 MqttMessage message; message = new MqttMessage(cmdInfo.getBytes()); message.setQos(0); client.publish(sendTopic, message); System.out.println("==send:"+sendTopic+"====res:"+resTopic); int in = 0; if (timeout > 0){ while (true){ System.out.println("==d====:"+in+"===="); Thread.sleep(100); if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){ res = mqttHandler.getRes(); System.out.println(res); //原来的 JSONObject oldObject = JSON.parseObject(cmdInfo); String oldDataType = oldObject.getObject("dataType", String.class); // String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-"); // String[] oldSnArr = oldThirdIdArr[0].split(":"); // String oldSn = oldSnArr[1]; //设备地址 // String[] oldNumberArr = oldThirdIdArr[1].split(":"); // int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号 //解析json JSONObject jsonObject = JSON.parseObject(res); String dataType = jsonObject.getObject("dataType", String.class); // String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-"); // String[] snArr = thirdIdArr[0].split(":"); // String sn = snArr[1]; //设备地址 // String[] numberArr = thirdIdArr[1].split(":"); // int num = Integer.parseInt(numberArr[1]); //设备灯序号 //它是字符串 if (dataType.equals("lightStatus") ){ //1.读取灯信息,2.调光的 //原来的 String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-"); String[] oldSnArr = oldThirdIdArr[0].split(":"); String oldSn = oldSnArr[1]; //设备地址 String[] oldNumberArr = oldThirdIdArr[1].split(":"); int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号 //解析json String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-"); String[] snArr = thirdIdArr[0].split(":"); String sn = snArr[1]; //设备地址 String[] numberArr = thirdIdArr[1].split(":"); int num = Integer.parseInt(numberArr[1]); //设备灯序号 //类型相等 System.out.println("====ddd:"+oldSn+"====sn:"+sn+"====ol:"+oldNum+"==nu:"+num); if ((oldDataType.equals("lightStatus") || oldDataType.equals("adjustLightController")) && oldSn.equals(sn) && (oldNum == num)){ //查看灯的信息 System.out.println("====ddd:"+res); return res; } } } in ++; if (in > timeout) return null; } } client.disconnect(); }catch (Exception e){ System.out.println("==dd=="+e); e.printStackTrace(); } }catch (Exception e){ System.out.println(e); e.printStackTrace(); } return null; } /** * 字节数组转16进制字符串 * @param b 字节数组 * @return 16进制字符串 * @throws */ public String bytes2HexString(byte[] b) { StringBuffer result = new StringBuffer(); String hex; for (int i = 0; i < b.length; i++) { hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } result.append(hex.toUpperCase()); } return result.toString(); } /** * 16进制字符串转字节数组 * @param src 16进制字符串 * @return 字节数组 * @throws */ public byte[] hexString2Bytes(String src) { int l = src.length() / 2; byte[] ret = new byte[l]; for (int i = 0; i < l; i++) { ret[i] = (byte) Integer .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue(); } return ret; } /** * 获取CRC32校验码 * @param src 16进制字符串 * @return CRC32校验码 */ public String getCRC32ByHexString2Bytes(String src) { CRC32 crc32 = new CRC32(); crc32.update(this.hexString2Bytes(src)); return Integer.toHexString((int) crc32.getValue()); } /** * 计算modbus CRC16校验码 * @param bytes 需要计算的数据 * @return */ public String getCRC(byte[] bytes) { // CRC寄存器全为1 int CRC = 0x0000ffff; // 多项式校验值 int POLYNOMIAL = 0x0000a001; int i, j; for (i = 0; i < bytes.length; i++) { CRC ^= ((int) bytes[i] & 0x000000ff); for (j = 0; j < 8; j++) { if ((CRC & 0x00000001) != 0) { CRC >>= 1; CRC ^= POLYNOMIAL; } else { CRC >>= 1; } } } // 结果转换为16进制 String result = Integer.toHexString(CRC).toUpperCase(); if (result.length() != 4) { StringBuffer sb = new StringBuffer("0000"); result = sb.replace(4 - result.length(), 4, result).toString(); } //高位在前地位在后 //return result.substring(2, 4) + " " + result.substring(0, 2); // 交换高低位,低位在前高位在后 return result.substring(2, 4)+result.substring(0, 2); } public String getCRC(String cmd) { byte[] bytes = this.hexString2Bytes(cmd); // CRC寄存器全为1 int CRC = 0x0000ffff; // 多项式校验值 int POLYNOMIAL = 0x0000a001; int i, j; for (i = 0; i < bytes.length; i++) { CRC ^= ((int) bytes[i] & 0x000000ff); for (j = 0; j < 8; j++) { if ((CRC & 0x00000001) != 0) { CRC >>= 1; CRC ^= POLYNOMIAL; } else { CRC >>= 1; } } } // 结果转换为16进制 String result = Integer.toHexString(CRC).toUpperCase(); if (result.length() != 4) { StringBuffer sb = new StringBuffer("0000"); result = sb.replace(4 - result.length(), 4, result).toString(); } //高位在前地位在后 //return result.substring(2, 4) + " " + result.substring(0, 2); // 交换高低位,低位在前高位在后 return result.substring(2, 4)+result.substring(0, 2); } public Object getRequestContent(HttpServletRequest request,String key){ return request.getParameter(key); } /** * 获取请求参数 * @param request 请求对象 * @param key 参数值 * @param type 参数类型 1 int 2 string * @return */ public Object getRequestContent(HttpServletRequest request,String key,Integer type){ if (type == 1){ // 获取 int 数据 Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key)); return keyId; }else if (type == 2){ String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString(); return keyStr.trim(); } return request.getParameter(key); } /** * 发送post请求 * @param url 请求地址 * @param paraMap 请求参数 * @return */ public String httpPost(String url,Map paraMap){ HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("accept", "*/*"); //设置Content-Type postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //添加请求参数 Set set = paraMap.keySet(); for (Object s : set) { postMethod.addParameter((String) s, (String) paraMap.get(s)); } String result = ""; try { int code = httpClient.executeMethod(postMethod); if (code == 200){ result = postMethod.getResponseBodyAsString(); } } catch (IOException e) { // e.printStackTrace(); } return result; } /** * 发送post请求 * @param url 请求地址 * @param paraMap 请求参数 * @param timeout 超时时间 * @return */ public String httpPost(String url,Map paraMap,int timeout){ HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout); PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("accept", "*/*"); //设置Content-Type postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //添加请求参数 Set set = paraMap.keySet(); for (Object s : set) { postMethod.addParameter((String) s, (String) paraMap.get(s)); } String result = ""; try { int code = httpClient.executeMethod(postMethod); if (code == 200){ result = postMethod.getResponseBodyAsString(); } } catch (IOException e) { // e.printStackTrace(); } return result; } /** * 通过id获取控制器型号名称 * @param id * @return */ public String getLampControlNameById(Integer id){ for (LampControlTypeEnum value : LampControlTypeEnum.values()) { if (value.getId().intValue() == id.intValue()){ return value.getName(); } } return ""; } /** * 通过控制器型号名称获取型号id * @param name * @return */ public Integer getLampControlIdByName(String name){ for (LampControlTypeEnum value : LampControlTypeEnum.values()) { if (value.getName().equals(name)){ return value.getId(); } } return 0; } /** * 获取文件的大小 * @param path 文件的路径 * @return 返回文件的大小(四舍五入) */ public String getFileSize(String path) throws IOException { String urlStr = path; if (!urlStr.contains("https://") && !urlStr.contains("http://")) { urlStr = "http://" + urlStr; } URL url = new URL(urlStr); URLConnection connection = url.openConnection(); long fileSize = connection.getContentLengthLong(); DecimalFormat decimalFormat = new DecimalFormat("0.00"); if (fileSize != -1) { double fileSizeMB = (double) fileSize / (1024 * 1024); return decimalFormat.format(fileSizeMB); } else { return null; } } /** * 计算两个经纬度之间的距离 * @param gpsFrom 第一个经纬度坐标点 * @param gpsTo 第二个经纬度坐标点 * @param ellipsoid 坐标系 * @return 返回两者之间的距离 */ public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) { //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离 GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo); return geoCurve.getEllipsoidalDistance(); } /** * 检查密码、手机号码、邮箱格式是否正确 * @param dataFormat 0:密码,1:手机,2:邮箱 * @return true、false */ public static Boolean checkDataFormat(String dataFormat, Integer type) { boolean isFlag; if (type == 2) { // 邮箱 isFlag = Pattern.matches(PATTERN_EMAIL, dataFormat); } else if (type == 1) { // 手机 isFlag = Pattern.matches(PATTERN_PHONE, dataFormat); } else { // 密码 isFlag = Pattern.matches(PATTERN, dataFormat); } return isFlag; } /** * 获取云盒气象站485设备列表 * @param devInfoEnum 枚举类数组 * @param version 语言版本 * @return 云盒气象站485设备列表 */ public static List getDevEnum(List devInfoEnum, Integer version) { List list = new ArrayList<>(); for (DevInfoEnum d : devInfoEnum) { String name; if (version == 0) { name = d.getNameCh(); } else if (version == 1) { name = d.getNameEn(); } else { name = d.getNameRu(); } list.add(new DevEnumVO(d.getId(), name)); } return list; } /** * 获取枚举类数组 * @return 枚举类数组 */ public static List addAllEnum() { List list = new ArrayList<>(); list.add(DevInfoEnum.LOUVER_BOX6); list.add(DevInfoEnum.WIND_DIRECTION); list.add(DevInfoEnum.WIND_SPEED); list.add(DevInfoEnum.RAINFALL); list.add(DevInfoEnum.SOLAR_RADIATION); list.add(DevInfoEnum.LOUVER_BOX10); list.add(DevInfoEnum.SOLAR_WIND_SPEED_DIRT); return list; } /** * 修改灯杆上绑定设备的设备类型 * @param devType 灯杆绑定的设备类型 * @param type 设备类型 * @param lampPoleId 灯杆id */ public void updateLampPoleDevType(String devType, Integer type, Integer lampPoleId) { String[] split = devType.split(","); String value = String.valueOf(type); StringJoiner joiner = new StringJoiner(","); for (String s : split) { if (!s.equals(value)) { joiner.add(s); } } String newDevType = joiner.toString(); LampPoleDTO lampPoleDTO = new LampPoleDTO(); lampPoleDTO.setId(lampPoleId); lampPoleDTO.setDevType(newDevType); lampPoleService.updateLampPoleDevType(lampPoleDTO); } /** * 获取策略内容描述 * @param policyType 策略类型 * @param cmd 指令内容 * @return 策略内容描述 */ public static String getLightStripContent(String policyType, String cmd) { String content; switch (policyType) { case "0": content = ("常亮(颜色:" + cmd + ")"); break; case "1": switch (cmd) { case "1": content = ("红灯呼吸"); break; case "2": content = ("绿灯呼吸"); break; case "3": content = ("蓝灯呼吸"); break; case "4": content = ("RGB呼吸"); break; case "5": content = ("黄灯呼吸"); break; case "6": content = ("紫灯呼吸"); break; default: content = ""; break; } break; case "2": switch (cmd) { case "1": content = ("红灯爆闪"); break; case "2": content = ("绿灯爆闪"); break; case "3": content = ("蓝灯爆闪"); break; case "4": content = ("白色爆闪"); break; case "5": content = ("7色爆闪"); break; case "6": content = ("黄灯爆闪"); break; case "7": content = ("紫灯爆闪"); break; default: content = ""; break; } break; case "3": content = ("关灯"); break; case "4": switch (cmd) { case "1": content = ("红灯闪烁"); break; case "2": content = ("绿灯闪烁"); break; case "3": content = ("蓝灯闪烁"); break; case "4": content = ("白色闪烁"); break; case "5": content = ("7色闪烁"); break; case "6": content = ("黄灯闪烁"); break; case "7": content = ("紫灯闪烁"); break; default: content = ""; break; } break; default: content = ""; break; } return content; } /** * 获取plc策略内容 * @param p plc策略内容对象 * @return plc策略内容 * @throws NoSuchFieldException 对象中没有该属性抛出的异常 * @throws IllegalAccessException 类型非法转换抛出的异常 */ public static List getPlcPolicyValue(PlcPolicyCmdDTO p) throws NoSuchFieldException, IllegalAccessException { List value = new ArrayList<>(); if (p.getBaseTimeType() == 0) { // 零点 for (int i = 1; i <= 6; i ++) { Field fieldStartTime = p.getClass().getDeclaredField("startTime" + i); fieldStartTime.setAccessible(true); String startTime = (String) fieldStartTime.get(p); if (startTime == null || startTime.isEmpty()) break; Field fieldEndTime = p.getClass().getDeclaredField("endTime" + i); fieldEndTime.setAccessible(true); String endTime = (String) fieldEndTime.get(p); // 亮度 Field fieldStartBright = p.getClass().getDeclaredField("bright" + i); fieldStartBright.setAccessible(true); Integer startBright = (Integer) fieldStartBright.get(p); // 色温 Field fieldStartColor = p.getClass().getDeclaredField("color" + i); fieldStartColor.setAccessible(true); Integer startColor = (Integer) fieldStartColor.get(p); if (endTime != null && !endTime.isEmpty()) { String tips = startTime + " - " + endTime + " 亮度" + startBright + "% 色温" + startColor + "k"; value.add(tips); Field fieldStartTime2 = p.getClass().getDeclaredField("startTime" + (i + 1)); fieldStartTime2.setAccessible(true); String startTime2 = (String) fieldStartTime2.get(p); // 亮度 Field fieldEndBright = p.getClass().getDeclaredField("endBright" + i); fieldEndBright.setAccessible(true); Integer endBright = (Integer) fieldEndBright.get(p); // 色温 Field fieldEndColor = p.getClass().getDeclaredField("endColor" + i); fieldEndColor.setAccessible(true); Integer endColor = (Integer) fieldEndColor.get(p); if (startTime2 != null && !startTime2.isEmpty()) { String tips1 = endTime + " - " + startTime2 + " 亮度" + endBright + "% 色温" + endColor + "k"; value.add(tips1); } else { String tips1 = endTime + " - " + " 亮度" + endBright + "% 色温" + endColor + "k"; value.add(tips1); break; } } else { String tips = startTime + " - " + " 亮度" + startBright + "% 色温" + startColor + "k"; value.add(tips); break; } } } else { // 日出日落 String startDelayTime = p.getStartDelayTime(); Integer startBright = p.getStartBright(); Integer startColor = p.getStartColor(); String tips1,tips2; int startTime = java.lang.Integer.parseInt(startDelayTime); if (startTime >= 0) { tips1 = "日出推迟" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k"; } else { startTime = -startTime; tips1 = "日出提前" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k"; } String endDelayTime = p.getEndDelayTime(); Integer endBright = p.getEndBright(); Integer endColor = p.getEndColor(); int endTime = java.lang.Integer.parseInt(endDelayTime); if (endTime >= 0) { tips2 = "日落推迟" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k"; } else { endTime = -endTime; tips2 = "日落提前" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k"; } value.add(tips1); value.add(tips2); } return value; } /** * 获取协议类型字符串 * @param protocolType 协议类型 * @return 协议类型字符串 */ public static String getProtocolTypeStr(Integer protocolType) { String protocolTypeStr; switch (protocolType) { case 12 : protocolTypeStr = ("铂胜lora"); break; case 11 : protocolTypeStr = ("PLC(有单灯,也有双灯控制器)"); break; case 10 : protocolTypeStr = ("WE-CON-4G20(双路控制)"); break; case 9 : protocolTypeStr = ("LC-6B11-J"); break; case 8 : protocolTypeStr = ("eMqtt"); break; case 7 : protocolTypeStr = ("oneNet"); break; case 6 : protocolTypeStr = ("LoraWAN"); break; case 5 : protocolTypeStr = ("zigbee"); break; case 4 : protocolTypeStr = ("gprs_direct"); break; case 3 : protocolTypeStr = ("nbIot"); break; case 2 : protocolTypeStr = ("rf mesh"); break; case 1 : protocolTypeStr = ("lora mesh"); break; default : protocolTypeStr = ("lorawan"); break; } return protocolTypeStr; } /** 向第三方请求post *@param requestMethod:请求方式 * @param url:路径 * @param param:参数 * @param ContentTypeEnum: 编码类型 * @return 返回类型字符串 */ public String sendHttp(String requestMethod,String url, String param,Integer timeOut,ContentTypeEnum typeEnum,String cookie) throws IOException { String result = ""; URL postUrl = new URL(url); // 打开连接 HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection(); // 设置是否向connection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true connection.setDoOutput(true); connection.setDoInput(true); if (timeOut == null || timeOut == 0){ connection.setConnectTimeout( 5000); //单位:毫秒 connection.setReadTimeout( 5000); //单位:毫秒 }else { connection.setConnectTimeout(timeOut * 1000); //单位:毫秒 connection.setReadTimeout(timeOut * 1000); //单位:毫秒 } // Set the post method. Default is GET connection.setRequestMethod(requestMethod.toUpperCase()); // Post 请求不能使用缓存 connection.setUseCaches(false); // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 connection.setInstanceFollowRedirects(true); // 进行编码 if (typeEnum == null){ //默认是"application/json;charset=utf-8" connection.setRequestProperty("Content-Type","application/json;charset=utf-8"); }else { connection.setRequestProperty("Content-Type",typeEnum.contentType); } if (cookie != null){ connection.setRequestProperty("Cookie",cookie); } // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 connection.connect(); if (!requestMethod.equals("GET") && !requestMethod.equals("get")){ DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致 // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面 out.writeBytes(param); out.flush(); out.close(); // flush and close } //读取服务器返回的数据 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { result += line; } reader.close(); connection.disconnect(); return result; } /** 向第三方请求post *@param request:请求方式 * @param url:路径 * @param param:参数 * @param token:令牌 * @param sessionId:会话id * @param timeOut:超时 * @param mark:标记Authorization是传哪种方式 * @param typeEnum: 编码类型 * @return 返回类型字符串 */ public String sendHttp(String requestMethod,String url, String param,String token,String sessionId,Integer timeOut,String mark,ContentTypeEnum typeEnum,String cookie) throws IOException { String result = ""; URL postUrl = new URL(url); // 打开连接 HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection(); // 设置是否向connection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true connection.setDoOutput(true); connection.setDoInput(true); // Set the post method. Default is GET connection.setRequestMethod(requestMethod.toUpperCase()); // Post 请求不能使用缓存 connection.setUseCaches(false); // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 connection.setInstanceFollowRedirects(true); // 进行编码 //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); if (typeEnum == null){ //默认是"application/json;charset=utf-8" connection.setRequestProperty("Content-Type","application/json;charset=utf-8"); }else { connection.setRequestProperty("Content-Type",typeEnum.contentType); } if (mark != null && mark.toLowerCase().equals("bearer")){ connection.setRequestProperty("Authorization","Bearer "+token); }else if(mark != null && mark.equals("api-key")) { connection.setRequestProperty("api-key"," "+token); }else { connection.setRequestProperty("Authorization",token); } if (cookie != null){ connection.setRequestProperty("Cookie",cookie); } if (sessionId != null){ connection.setRequestProperty("SessionId"," "+sessionId); } if (timeOut == null || timeOut == 0){ connection.setConnectTimeout( 5000); //单位:毫秒 connection.setReadTimeout( 5000); //单位:毫秒 }else { connection.setConnectTimeout(timeOut * 1000); //单位:毫秒 connection.setReadTimeout(timeOut * 1000); //单位:毫秒 } // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 connection.connect(); if (!requestMethod.equals("GET") && !requestMethod.equals("get")){ DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致 // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面 out.writeBytes(param); out.flush(); out.close(); // flush and close } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { result += line; } reader.close(); connection.disconnect(); return result; } /** * 添加设备onenet * @param deviceId * @return */ public String addDeviceOnenet(String deviceId){ JSONObject device = new JSONObject(); device.put("title",deviceId); device.put("protocol","LWM2M"); JSONObject authInfo = new JSONObject(); authInfo.put(deviceId,deviceId); device.put("auth_info",authInfo); String url="http://api.heclouds.com/devices"; String token = "HpumrF3BKBo3mOFIhkyf5MtIIOc="; String respone = null; try { respone = this.sendHttp("post", url, device.toString(), token, null, 5, "api-key", ContentTypeEnum.CONTENT_TYPE_JSON,null); } catch (IOException e) { throw new RuntimeException(e); } return respone; } // 修改灯杆类型 public void setPoleType(Integer poleId,Integer type){ if (poleId != 0 || poleId != null){ LampPoleDTO lampPoleDTO = lampPoleService.getLampPoleDTOById(poleId); String[] devArr = new String[]{}; if(lampPoleDTO.getDevType() != null){ devArr = lampPoleDTO.getDevType().split(","); } //是否包含某个元素 boolean ifContain = Arrays.asList(devArr).contains(type); if (ifContain == false){ //字符串数组转换list,再添加元素 List list = new ArrayList<>(Arrays.asList(devArr)); list.add(type.toString()); //list数组按规定拼接成字符串 String newDevType = list.stream().collect(Collectors.joining(",")); lampPoleDTO.setId(poleId); lampPoleDTO.setDevType(newDevType); lampPoleService.updateById(lampPoleDTO); } } } /** * 操作日志 * @param request HttpServletRequest类型 * @param operation 操作(添加/删除/编辑) * @param remark 标记(中/英/俄,拼接设备的各种需要的信息) * @param type 类型(0-中文,1-英语,2-俄文) * @param operaType 操作类型(0 未定义操作,1 添加,2 删除,3 编辑,4 指令,5 退出登录 * @param devtype '设备类型(0 非设备,1 路灯,2 灯杆,3 回路,4 井盖,5 垃圾桶) * @param deviceName 设备名称/或编号 * @param area 区域名 * @param section 路段名 * @param sn 设备sn码 * @param sectionId 路段id * @param areaId 区域id * @param id 设备id * @param sql_log 最后一条sql语句 */ public void addOpertaionLog(HttpServletRequest request,String operation, String remark,Integer type,Integer operaType,Integer devtype,String deviceName,String area,String section,String sn ,Integer sectionId ,Integer areaId ,Integer id,String sql_log){ String ip = ""; if (request.getParameter("ip") != null){ ip = request.getParameter("ip"); }else { ip = request.getServerName(); } try { String location = this.getLocationByIp(ip); Date day = new Date(); SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String updateTime = sdf.format(day); String username = request.getParameter("username"); Integer userId = this.getUser(request).getId(); Integer os = request.getParameter("os") == null ? 0 : Integer.parseInt(request.getParameter("os")); OperationLogDTO operationLogDTO = new OperationLogDTO(); operationLogDTO.setTime(updateTime); operationLogDTO.setAcount(username); operationLogDTO.setOperation(operation); operationLogDTO.setRemark(remark); operationLogDTO.setOs(os); operationLogDTO.setType(type); operationLogDTO.setOperaType(operaType); operationLogDTO.setUserId(userId); operationLogDTO.setDeviceName(deviceName); operationLogDTO.setArea(area); operationLogDTO.setSection(section); operationLogDTO.setSn(sn); operationLogDTO.setAreaId(areaId); operationLogDTO.setSectionId(sectionId); operationLogDTO.setDevId(id); operationLogDTO.setSqlLog(sql_log); operationLogDTO.setIpAddr(ip); operationLogDTO.setLocation(location); operationLogService.add(operationLogDTO); } catch (IOException e) { throw new RuntimeException(e); } } private String getLocationByIp(String ip) throws IOException { //把域名都转换成ip地址 ip = InetAddress.getByName(ip).getHostAddress(); IpInfoDTO infoDTO = ipInfoService.getDataByIp(ip); String location = ""; if (infoDTO == null){ IpInfoDTO newInfoDTO = new IpInfoDTO(); if (ip.equals("127.0.0.1")){ //本地添加 location = "服务器本地"; newInfoDTO.setLocation(location); newInfoDTO.setIpAddr(ip); ipInfoService.add(newInfoDTO); }else { String url = "https://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&oe=utf8"; JSONObject jsonObject = new JSONObject(); jsonObject.put("query",ip); jsonObject.put("co",null); jsonObject.put("resource_id",600); jsonObject.put("oe","utf8"); String respone = this.sendHttp("get", url, jsonObject.toString(), 4, ContentTypeEnum.CONTENT_TYPE_JSON,null); if (respone != null){ JSONObject responeJson = JSON.parseObject(respone); String status = responeJson.getString("status"); if (status.equals("0")){ //成功 //数组 JSONArray jsonArray = responeJson.getJSONArray("data"); JSONObject item = (JSONObject)(jsonArray.get(0)); location = item.getString("location"); newInfoDTO.setLocation(location); newInfoDTO.setIpAddr(ip); ipInfoService.add(newInfoDTO); } } } }else { location = infoDTO.getLocation(); } return location; } /** * 翻译故障信息 - 中英 * @param alarmStr * @return */ public String changeAlarm(String alarmStr){ if (alarmStr == null || alarmStr.length() == 0) return "Unknown error"; HashMap hashMap = new HashMap<>(); hashMap.put("供电异常","Power supply anomaly"); hashMap.put("灯闪","Light flicker"); hashMap.put("灯坏","Light bad"); hashMap.put("LED驱动故障","LED drive failure"); hashMap.put("灯坏或LED驱动故障","Light bad or LED drive failure"); hashMap.put("电压过低","Low voltage"); hashMap.put("电压过高","Overvoltage"); hashMap.put("开灯故障","Turn on the lights"); hashMap.put("离线故障","Offline fault"); String[] arr = alarmStr.split(",");//内容 List stringList = new ArrayList<>();//存放 for (String item: arr) { String value = hashMap.get(item); if (value == null){ stringList.add("Unknown error"); }else { stringList.add(value); } } //字符串拼接 return String.join(".", stringList); } /** * 翻译故障信息 - 中俄 * @param alarmStr * @return */ public String changeAlarmRu(String alarmStr){ if (alarmStr == null || alarmStr.length() == 0) return "ошибка"; HashMap hashMap = new HashMap<>(); hashMap.put("供电异常","Аномальный источник питания"); hashMap.put("灯闪","вспышка лампы"); hashMap.put("灯坏","лампочка"); hashMap.put("LED驱动故障","Ошибка LED-драйвера"); hashMap.put("灯坏或LED驱动故障","неисправность лампы или привода светодиода"); hashMap.put("电压过低","понижение напряжения"); hashMap.put("电压过高","избыточное напряжение"); hashMap.put("开灯故障","неисправность зажигания"); hashMap.put("离线故障","автономный отказ"); String[] arr = alarmStr.split(",");//内容 List stringList = new ArrayList<>();//存放 for (String item: arr) { String value = hashMap.get(item); if (value == null){ stringList.add("ошибка"); }else { stringList.add(value); } } //字符串拼接 return String.join(".", stringList); } /** * 上传文件/图片/音频 * @param file 文件 * @param image 图片 * @param video 音频 * @param title 名称 * @return * @throws Exception */ public String uploadFile(MultipartFile file, MultipartFile image,MultipartFile video, String title) throws Exception { String rootPath = System.getProperty("user.dir"); String systemName = System.getProperty("os.name"); if (systemName.toLowerCase().contains("windows")){ //windows int lastedIndex = rootPath.lastIndexOf("\\"); rootPath = rootPath.substring(0,lastedIndex); //工程根目录 }else { //os/linux int lastedIndex = rootPath.lastIndexOf("/"); rootPath = rootPath.substring(0,lastedIndex); //工程根目录 } File imagePath; //图⽚存放地址 File fileRealPath; //⽂件存放地址 File videoPath; //音视频存在地址 if (file == null && image == null && video == null) return "0001"; //文件\图片\音频不能都不传 //获取⽂件名称 if (file != null){ //判断文件的类型 boolean b = this.fileType(file,2); if (b == false) return "0002"; //类型不对 String pathName = "/upload/files"; fileRealPath = new File(rootPath+pathName); //判断⽂件夹是否存在 if(!fileRealPath.exists()){ //不存在,创建 fileRealPath.mkdirs(); } String fileName = file.getOriginalFilename(); //创建⽂件存放地址 File resultPath = new File(fileRealPath+"/"+fileName); file.transferTo(resultPath); System.out.println("resultPath:"+resultPath.getCanonicalPath()); return pathName+"/"+fileName; } if (image != null){ //图片 //判断文件的类型 boolean b = this.fileType(image,1); if (b == false) return "0002"; //类型不对 String pathName = "/upload/images"; imagePath = new File(rootPath+pathName); if(!imagePath.exists()){ //不存在,创建 imagePath.mkdirs(); } String imageName = image.getOriginalFilename(); //创建图⽚存放地址 File imageResultPath = new File(imagePath+"/"+imageName); image.transferTo(imageResultPath); System.out.println("imageResultPath:"+imageResultPath.getCanonicalPath()); return pathName+"/"+imageName; } if (video != null){ //音频 //判断文件的类型 boolean b = this.fileType(video,3); if (b == false) return "0002"; //类型不对 String pathName = "/upload/videos"; videoPath = new File(rootPath+pathName); if(!videoPath.exists()){ //不存在,创建 videoPath.mkdirs(); } String videoName = video.getOriginalFilename(); //创建图⽚存放地址 File videoResultPath = new File(videoPath+"/"+videoName); video.transferTo(videoResultPath); return pathName+"/"+videoName; } return "0003"; //未知问题 } private boolean fileType(MultipartFile tempFile,int type) throws IOException { InputStream inputStream = tempFile.getInputStream(); byte[] buffer = new byte[8]; inputStream.read(buffer); String magicNumber = bytes2HexString(buffer); if (magicNumber.substring(0,4).equals("FFD8") && type == 1) { // ⽂件是JPEG/jpg类型 } else if (magicNumber.substring(0,8).equals("89504E47") && type == 1) { // ⽂件是PNG类型 } else if (magicNumber.substring(0,8).equals("47494638") && type == 1) { // ⽂件是GIF类型 }else if (magicNumber.substring(0,8).equals("25504446") && type == 2) { // ⽂件是PDF类型 } else if (magicNumber.substring(0,8).equals("504B0304") && type == 2) { // ⽂件是DOCX类型 } else if (magicNumber.substring(0,8).equals("32303230") && type == 2){ //⽂件是txt类型 }else if (magicNumber.substring(0,6).equals("494433") && type == 3){//4944330400000000 // ⽂件是mp3类型 }else { // ⽂件类型未知 return false; //文件类型不对 } return true; } /** * 生成日志,保存在本地 * @param fileName 文件名 * @param content 日志内容 * @throws IOException */ public void setLog(String fileName,String content) throws IOException { String rootPath = System.getProperty("user.dir"); int lastedIndex = rootPath.lastIndexOf("/"); rootPath = rootPath.substring(0,lastedIndex); //工程根目录 String logFilePath = rootPath+"/upload/log"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建日志文件 File logFile = new File(logFilePath); if (!logFile.exists()) { logFile.mkdirs(); //创建文件夹 } String record = String.format("%s", content+"===="+dateFormat.format(new Date())); File file = new File(logFilePath +"/"+ fileName); try (FileWriter writer = new FileWriter(file, true)) { writer.write(record); writer.flush(); writer.write("\n"); // 添加一个空行,以便下次写入时定位到下一行 } catch (IOException e) { e.printStackTrace(); } } /** * 获取国标摄像头播放地址 * @param gbAddress 国标摄像头地址 * @param res * @param vType * @param sectionId * @return * @throws IOException */ public String getGbPlayAddress(String gbAddress,String res,String vType,Integer sectionId ) throws IOException { //Integer gb_id = Integer.valueOf(gbAddress.substring(gbAddress.length() - 7)); String gbId = gbAddress.substring(gbAddress.length() - 7); String url = "http://"+ToolUtils.gbHost+":8060/index/api/getMediaList?secret=weclouds123"; if (res == null) res = this.sendHttp("get",url,null,5,null,null); JSONObject parseObject = JSON.parseObject(res); int number = Integer.parseInt(gbId); gbId = String.format("%08x", number); String address = ""; if (gbAddress.equals("34020000001320000120")) gbId = "55667788"; if (parseObject != null && parseObject.getInteger("code") != null && parseObject.getInteger("code") == 0){ List list = parseObject.getJSONArray("data") == null ? new ArrayList<>() : parseObject.getJSONArray("data"); int flag = 0; for (Object obj:list) { JSONObject item = (JSONObject) obj; String stream = (String) item.get("stream"); Integer bytesSpeed = item.getInteger("bytesSpeed"); if (stream.toLowerCase().equals(gbId.toLowerCase()) && bytesSpeed != 0){ flag = 1; break; } } if (flag == 1){ //this.setLog("get_gb_play_address.txt",gbAddress+" old address "+this.getUser().getUsername()); if (vType == null || vType.isEmpty()){ address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv"; }else { address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8"; } }else { //this.setLog("get_gb_play_address.txt",gbAddress+" new address--- "+this.getUser().getUsername()); GbPlayDTO oneData = gbPlayService.getOneData(gbAddress); long currentTimeMillis = System.currentTimeMillis(); long seconds = currentTimeMillis / 1000; if (oneData == null || seconds - oneData.getTime() > 5){ Integer id = Integer.valueOf(gbAddress.substring(gbAddress.length() - 7)); String resUrl = "http://"+ToolUtils.gbHost+":8089/api/play/"+gbAddress+"/"+gbAddress+"/"+id; String res2 = this.sendHttp("get", resUrl, null, 10, null, null); JSONObject jsonObject = JSON.parseObject(res2); if (oneData == null){ oneData.setGbAddress(gbAddress); oneData.setTime(seconds); gbPlayService.addData(oneData); }else { oneData.setTime(seconds); gbPlayService.updataData(oneData); } } if (vType == null || vType.isEmpty()){ address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv"; }else { address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8"; } } if (gbAddress.equals("34020000001320001079") || gbAddress.equals("34020000001320000762") || gbAddress.equals("3402000000132000128")){ address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.mp4"; }else { address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8"; } if (sectionId.equals(739) || sectionId.equals(593)){ address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv"; } if (gbAddress.equals("34020000001320000967")){ } String sendTopic = "/welampiot/gb28181/getImage"; String backTopic = "/welampiot/gb28181/getImage"; JSONObject jsonObject = new JSONObject(); jsonObject.put("gb_address",gbAddress); this.sendMqttCmd(sendTopic,jsonObject.toString(),backTopic,0); } return address; } /** * 请求 compress.zlib://这压缩类型接口 * @param url 网址 * @return 返回请求后的json字符串 */ public String zlibNetwork(String url){ try { // 使用URL类来创建URL对象 URL resourceUrl = new URL(url); // 打开连接 GZIPInputStream gzipInputStream = new GZIPInputStream(resourceUrl.openStream()); // 创建BufferedReader来读取数据 BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream)); String line; StringBuilder content = new StringBuilder(); // 读取每一行 while ((line = reader.readLine()) != null) { content.append(line); } // 输出结果 return content.toString(); } catch (IOException e) { e.printStackTrace(); } return ""; } // 天气信息翻译 public String weatherTranslateEn(String code){ HashMap map = new HashMap<>(); map.put("100","Sunny/Clear"); map.put("101","Cloudy"); map.put("102","Few Clouds"); map.put("103","Partly Cloudy"); map.put("104","Overcast"); map.put("200","Windy"); map.put("201","Calm"); map.put("202","Light Breeze"); map.put("203","Moderate/Gentle Breeze"); map.put("204","Fresh Breeze"); map.put("205","Strong Breeze"); map.put("206","High Wind, Near Gale"); map.put("207","Gale"); map.put("208","Strong Gale"); map.put("209","Storm"); map.put("210","Violent Storm"); map.put("211","Hurricane"); map.put("212","Tornado"); map.put("213","Tropical Storm"); map.put("300","Shower Rain"); map.put("301","Heavy Shower Rain"); map.put("302","Thundershower"); map.put("303","Heavy Thunderstorm"); map.put("304","Thundershower with hail"); map.put("305","Light Rain"); map.put("306","Moderate Rain"); map.put("307","Heavy Rain"); map.put("308","Extreme Rain"); map.put("309","Drizzle Rain"); map.put("310","Storm"); map.put("311","Heavy Storm"); map.put("312","Severe Storm"); map.put("313","Freezing Rain"); map.put("314","Light to moderate rain"); map.put("315","Moderate to heavy rain"); map.put("316","Heavy rain to storm"); map.put("317","Storm to heavy storm"); map.put("318","Heavy to severe storm"); map.put("399","Rain"); map.put("400","Light Snow"); map.put("401","Moderate Snow"); map.put("402","Heavy Snow"); map.put("403","Snowstorm"); map.put("404","Sleet"); map.put("405","Rain And Snow"); map.put("406","Shower Snow"); map.put("407","Snow Flurry"); map.put("408","Light to moderate snow"); map.put("409","Moderate to heavy snow"); map.put("410","Heavy snow to snowstorm"); map.put("499","Snow"); map.put("500","Mist"); map.put("501","Foggy"); map.put("502","Haze"); map.put("503","Sand"); map.put("504","Dust"); map.put("507","Duststorm"); map.put("508","Sandstorm"); map.put("509","Dense fog"); map.put("510","Strong fog"); map.put("511","Moderate haze"); map.put("512","Heavy haze"); map.put("513","Severe haze"); map.put("514","Heavy fog"); map.put("515","Extra heavy fog"); map.put("900","Hot"); map.put("901","Cold"); map.put("999","Unknown"); return map.get(code) == null ? "":map.get(code); } public String weatherTranslateCn(String code){ HashMap map = new HashMap<>(); map.put("100","晴"); map.put("101","多云"); map.put("102","少云"); map.put("103","晴间多云"); map.put("104","阴"); map.put("200","有风"); map.put("201","平静"); map.put("202","微风"); map.put("203","和风"); map.put("204","清风"); map.put("205","强风/劲风"); map.put("206","疾风"); map.put("207","大风"); map.put("208","烈风"); map.put("209","风暴"); map.put("210","狂爆风"); map.put("211","飓风"); map.put("212","龙卷风"); map.put("213","热带风暴"); map.put("300","阵雨"); map.put("301","强阵雨"); map.put("302","雷阵雨"); map.put("303","强雷阵雨"); map.put("304","雷阵雨伴有冰雹"); map.put("305","小雨"); map.put("306","中雨"); map.put("307","大雨"); map.put("308","极端降雨"); map.put("309","毛毛雨/细雨"); map.put("310","暴雨"); map.put("311","大暴雨"); map.put("312","特大暴雨"); map.put("313","冻雨"); map.put("314","小到中雨"); map.put("315","中到大雨"); map.put("316","大到暴雨"); map.put("317","暴雨到大暴雨"); map.put("318","大暴雨到特大暴雨"); map.put("399","雨"); map.put("400","小雪"); map.put("401","中雪"); map.put("402","大雪"); map.put("403","暴雪"); map.put("404","雨夹雪"); map.put("405","雨雪天气"); map.put("406","阵雨夹雪"); map.put("407","阵雪"); map.put("408","小到中雪"); map.put("409","中到大雪"); map.put("410","大到暴雪"); map.put("499","雪"); map.put("500","薄雾"); map.put("501","雾"); map.put("502","霾"); map.put("503","扬沙"); map.put("504","浮尘"); map.put("507","沙尘暴"); map.put("508","强沙尘暴"); map.put("509","浓雾"); map.put("510","强浓雾"); map.put("511","中度霾"); map.put("512","重度霾"); map.put("513","严重霾"); map.put("514","大雾"); map.put("515","特强浓雾"); map.put("900","热"); map.put("901","冷"); map.put("999","未知"); return map.get(code) == null ? "":map.get(code); } public String weatherTranslateRu(String code){ HashMap map = new HashMap<>(); map.put("100","чинг"); map.put("101","облачно"); map.put("102","Меньше облако"); map.put("103","Ясная и облачная"); map.put("104","инь"); map.put("200","дует"); map.put("201","спокойствие"); map.put("202","ветерок"); map.put("203","зефир"); map.put("204","Свежий ветер"); map.put("205","Сильный ветер/сильный ветер"); map.put("206","шквал"); map.put("207","ветер"); map.put("208","шторм"); map.put("209","шторм"); map.put("210","Сильный ветер"); map.put("211","ураган"); map.put("212","Торнадо"); map.put("213","Тропический шторм"); map.put("300","ливень"); map.put("301","Сильный душ"); map.put("302","Грозовой дождь"); map.put("303","Сильный грозовой дождь"); map.put("304","Ливень сопровождается градом"); map.put("305","дождик"); map.put("306","Средний дождь"); map.put("307","дождь"); map.put("308","Экстремальный дождь"); map.put("309","Дождик/мелкий дождь"); map.put("310","Проливной дождь"); map.put("311","Сильный дождь"); map.put("312","Сильный ливень"); map.put("313","Ледяной дождь"); map.put("314","Немного дождя"); map.put("315","Под дождём"); map.put("316","Большой до грозы"); map.put("317","От грозы до грозы"); map.put("318","Сильные ливни, сильные ливни"); map.put("399","дождь"); map.put("400","Мелкий снежок"); map.put("401","средний снег"); map.put("402","снегопад"); map.put("403","Снежная буря"); map.put("404","Дождь и снег"); map.put("405","Дождливая и снежная погода"); map.put("406","Дождь и снег"); map.put("407","снежный"); map.put("408","Маленький до снега"); map.put("409","Прямо в снег"); map.put("410","От большой до снежной бури"); map.put("499","снег"); map.put("500","дымка"); map.put("501","туман"); map.put("502","мгла"); map.put("503","янша"); map.put("504","пыль"); map.put("507","Песчаная буря"); map.put("508","Сильная песчаная буря"); map.put("509","Густой туман"); map.put("510","Сильный густой туман"); map.put("511","Умеренный туман"); map.put("512","Тяжелая смола"); map.put("513","Туман"); map.put("514","Сильный туман"); map.put("515","Густой туман"); map.put("900","горячая"); map.put("901","холодно"); map.put("999","неизвестный"); return map.get(code) == null ? "":map.get(code); } /** * 发送wifimqtt指令 * @param sendTopic 发送的topic * @param cmdInfo 发送的指令内容 * @param resTopic 接收指令返回的topic * @param timeout 指令超时时间,默认是4s * @return */ public String sendWifiMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){ MqttClient client; String res = ""; if (timeout == null || timeout == 0) timeout = 4; try { try { client=new MqttClient(wifiMqttConfig.getUrl(),wifiMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence()); MqttConnectOptions options=new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(wifiMqttConfig.getUsername()); options.setPassword(wifiMqttConfig.getPassword().toCharArray()); options.setConnectionTimeout(wifiMqttConfig.getTimeout()); options.setKeepAliveInterval(wifiMqttConfig.getKeepalive()); mqttHandler.setTopic(resTopic); // 设置回调 client.setCallback(mqttHandler); // 建立连接 client.connect(options); // MqttCustomerClient.setClient(client); client.subscribe(resTopic); // 消息发布所需参数 MqttMessage message; if (cmdInfo instanceof String){ message = new MqttMessage(((String) cmdInfo).getBytes()); }else { message = new MqttMessage((byte[]) cmdInfo); } message.setQos(0); client.publish(sendTopic, message); int in = 0; while (true){ Thread.sleep(1000); if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){ res = mqttHandler.getRes(); break; } in ++; if (in > 30) break; } client.disconnect(); }catch (Exception e){ e.printStackTrace(); } }catch (Exception e){ e.printStackTrace(); } return res; } // 风向信息翻译 public String windTranslateEn(int code,int devType){ ArrayList data = new ArrayList<>(); if (devType == 7){ data.add("North wind"); data.add("northeast wind"); data.add("East wind"); data.add("Southeast wind"); data.add("South wind"); data.add("Southwest wind"); data.add("West Wind"); data.add("Northwest wind"); }else { data.add("North northeast"); data.add("Northeast"); data.add("East Northeast"); data.add("Due east"); data.add("Southeast to East"); data.add("Southeast"); data.add("Southeast to South"); data.add("Due south"); data.add("Southwest to South"); data.add("Southwest"); data.add("Southwest by West"); data.add("due west"); data.add("Northwest by West"); data.add("Northwest"); data.add("Northwest northwest"); data.add("Due north"); } return data.get(code) == null ? "" : data.get(code); } // 风向信息翻译 public String windTranslateCn(int code,int devType){ ArrayList data = new ArrayList<>(); if (devType == 7){ data.add("北风"); data.add("东北风"); data.add("东风"); data.add("东南风"); data.add("南风"); data.add("西南风"); data.add("西风"); data.add("西北风"); }else { data.add("东北偏北"); data.add("东北"); data.add("东北偏东"); data.add("正东"); data.add("东南偏东"); data.add("东南"); data.add("东南偏南"); data.add("正南"); data.add("西南偏南"); data.add("西南"); data.add("西南偏西"); data.add("正西"); data.add("西北偏西"); data.add("西北"); data.add("西北偏北"); data.add("正北"); } return data.get(code) == null ? "" : data.get(code); } // 风向信息翻译 public String windTranslateRn(int code,int devType){ ArrayList data = new ArrayList<>(); if (devType == 7){ data.add("Северный ветер"); data.add("северо-восточный ветер"); data.add("Восточный ветер"); data.add("Юго-восточный ветер"); data.add("Южный ветер"); data.add("Юго-западный ветер"); data.add("Западный ветер"); data.add("Северо-западный ветер"); }else { data.add("Северо-Восток, Север"); data.add("В северо-восточной"); data.add("Северо-Восток"); data.add("восток"); data.add("Юго-Восток, северо-Восток"); data.add("В юго-восточной"); data.add("Юго-Восток, юго-Запад"); data.add("юг"); data.add("Юго-Запад, юго-Запад"); data.add("Юго-западный"); data.add("Юго-Запад, Запад"); data.add("Западу от"); data.add("Северо-Запад"); data.add("Северо -"); data.add("Северо-Запад, Север"); data.add("северное"); } return data.get(code) == null ? "" : data.get(code); } // 获取国标摄像头播放地址 public String getOnvifPlayAddress(String num,Integer model,String stream) throws IOException { String url = "http://"+ToolUtils.gbHost+":8060/index/api/getMediaList?secret=weclouds123"; String res = this.sendHttp("get",url,null,5,null,null); String address = ""; if (res != null){ JSONObject parseObject = JSON.parseObject(res); Integer code = parseObject.getInteger("code"); if (code == 0){ //成功 int flag = 0; JSONArray data = parseObject.getJSONArray("data"); for (Object obj:data) { JSONObject temp = (JSONObject)obj; String resStream = temp.getString("stream"); Integer bytesSpeed = temp.getInteger("bytesSpeed"); if (resStream.toLowerCase().equals(stream.toLowerCase()) && !bytesSpeed.equals(0)){ flag = 1; break; } } if (flag == 1){ address = "https://gb.lampmind.com:8087/gb3/live/"+stream+"/hls.m3u8"; }else { String top = ""; if (model == 0){ top = "WEGW"; } else if (model == 1 || model == 5) { top = "WEGW2"; }else { top = "WEGW3"; } JSONObject json = new JSONObject(); json.put("reqId", 20); json.put("msgType", "startStream"); json.put("op", "W"); JSONObject jsonStream = new JSONObject(); jsonStream.put("uuid", stream); json.put("prop", jsonStream); String sendData = json.toString(); String sendTopic = "/"+top+"/DevManagerIn/"+num; String backTopic = "/"+top+"/DevManagerIn/"+num; String back = this.sendWifiMqttCmd(sendTopic, sendData, backTopic, 5); address = "https://gb.lampmind.com:8087/gb3/live/"+stream+"/hls.m3u8"; } return address; } } return address; } }