diff --git a/user-service/src/main/java/com/mh/user/strategy/ModbusProtocolStrategy.java b/user-service/src/main/java/com/mh/user/strategy/ModbusProtocolStrategy.java index 9a74247..c273faf 100644 --- a/user-service/src/main/java/com/mh/user/strategy/ModbusProtocolStrategy.java +++ b/user-service/src/main/java/com/mh/user/strategy/ModbusProtocolStrategy.java @@ -62,7 +62,7 @@ public class ModbusProtocolStrategy implements ProtocolStrategy { // 地址(1) + 功能码(1) + 寄存器地址(2) + 数据域(2) + crc校验 str = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(meterManageEntity.getMtCode()), 2) // 设备地址 + ExchangeStringUtil.addZeroForNum(meterManageEntity.getFuncCode(), 2) // 功能码 - + ExchangeStringUtil.addZeroForNum(meterManageEntity.getRegisterAddr(), 4) // 寄存器地址 + + ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(meterManageEntity.getRegisterAddr()), 4) // 寄存器地址 + ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf(meterManageEntity.getRegisterSize())), 4); // 读取寄存器个数 // 循环冗余校验 String checkWord = ExchangeStringUtil.getStrCRC16(str); //CRC16校验 @@ -111,9 +111,12 @@ public class ModbusProtocolStrategy implements ProtocolStrategy { sValue = ExchangeStringUtil.hexToDec(data); if (deviceCodeParamEntity.getDigit() == 0) { sValue = String.valueOf(Long.parseLong(sValue)); - } else { + } else if (deviceCodeParamEntity.getDigit() < 0) { + sValue = String.valueOf(Long.parseLong(sValue)) + ExchangeStringUtil.addZeroForNum("0", -deviceCodeParamEntity.getDigit()); + } + else { // 保留位数 - sValue = (new BigDecimal(sValue)).divide(new BigDecimal(String.valueOf(deviceCodeParamEntity.getDigit() * 10)), 2, RoundingMode.HALF_UP).toString(); + sValue = (new BigDecimal(sValue)).divide(new BigDecimal(ExchangeStringUtil.rightAddZeroForNum("1", deviceCodeParamEntity.getDigit()+1)), 2, RoundingMode.HALF_UP).toString(); } break; case 2: diff --git a/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java b/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java index ce7dfed..9d0d21e 100644 --- a/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java +++ b/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java @@ -30,7 +30,7 @@ import java.util.regex.Pattern; */ public class ExchangeStringUtil { - public static void main(String args[]){ + public static void main(String args[]) { // int ieee754Int = Integer.parseInt(str, 16); // float realValue = Float.intBitsToFloat(ieee754Int); @@ -63,6 +63,7 @@ public class ExchangeStringUtil { /** * 获取到对应的buffer + * * @param ctx * @param sendStr * @return @@ -80,23 +81,25 @@ public class ExchangeStringUtil { /** * double转换为String :当为整数时,只显示整数,当小数时直接显示小数 + * * @param num * @return */ - public static String doubleTrans1(double num){ - if(num % 1.0 == 0){ - return String.valueOf((long)num); + public static String doubleTrans1(double num) { + if (num % 1.0 == 0) { + return String.valueOf((long) num); } return String.valueOf(num); } /** * 获取String中的数值 + * * @param result * @return */ public static String getNumFromString(String result) { - String regEx="[^0-9]"; + String regEx = "[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(result); return m.replaceAll("").trim(); @@ -104,6 +107,7 @@ public class ExchangeStringUtil { /** * 获取检验位值,update by ljf on 2020-06-02 + * * @param result * @return */ @@ -112,8 +116,8 @@ public class ExchangeStringUtil { byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(result); int checkNum = CRC16.CRC16_MODBUS(strOrder); String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); - checkWord = ExchangeStringUtil.addZeroForNum(checkWord,4); - checkWord = checkWord.substring(2,4) + checkWord.substring(0,2); + checkWord = ExchangeStringUtil.addZeroForNum(checkWord, 4); + checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); result = result + checkWord; return result; } @@ -123,8 +127,8 @@ public class ExchangeStringUtil { byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(result); int checkNum = CRC16.CRC16_MODBUS(strOrder); String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); - checkWord = ExchangeStringUtil.addZeroForNum(checkWord,4); - checkWord = checkWord.substring(2,4) + checkWord.substring(0,2); + checkWord = ExchangeStringUtil.addZeroForNum(checkWord, 4); + checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); return checkWord; } @@ -141,6 +145,7 @@ public class ExchangeStringUtil { /** * 字符串不足补“0” + * * @param str * @param strLength * @return @@ -159,8 +164,30 @@ public class ExchangeStringUtil { return str; } + /** + * 字符串不足右边补“0” + * + * @param str + * @param strLength + * @return + */ + public static String rightAddZeroForNum(String str, int strLength) { + int strLen = str.length(); + if (strLen < strLength) { + while (strLen < strLength) { + StringBuffer sb = new StringBuffer(); +// sb.append("0").append(str);// 左补0 + sb.append(str).append("0");//右补0 + str = sb.toString(); + strLen = str.length(); + } + } + return str; + } + /** * ip地址转换成16进制long + * * @param ipString * @return */ @@ -175,19 +202,20 @@ public class ExchangeStringUtil { /** * ip地址转换成16进制long + * * @param ipString * @return */ public static Long ipToLong(String ipString) { Long[] ip = new Long[4]; - int pos1= ipString.indexOf("."); - int pos2= ipString.indexOf(".",pos1+1); - int pos3= ipString.indexOf(".",pos2+1); - ip[0] = Long.parseLong(ipString.substring(0 , pos1)); - ip[1] = Long.parseLong(ipString.substring(pos1+1 , pos2)); - ip[2] = Long.parseLong(ipString.substring(pos2+1 , pos3)); - ip[3] = Long.parseLong(ipString.substring(pos3+1)); - return (ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3]; + int pos1 = ipString.indexOf("."); + int pos2 = ipString.indexOf(".", pos1 + 1); + int pos3 = ipString.indexOf(".", pos2 + 1); + ip[0] = Long.parseLong(ipString.substring(0, pos1)); + ip[1] = Long.parseLong(ipString.substring(pos1 + 1, pos2)); + ip[2] = Long.parseLong(ipString.substring(pos2 + 1, pos3)); + ip[3] = Long.parseLong(ipString.substring(pos3 + 1)); + return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; } public static String splitData(String str, String strStart, String strEnd) { @@ -198,8 +226,8 @@ public class ExchangeStringUtil { public static String endData(String str, String strStart) { String tempStr; - String str1=str.substring(0, str.indexOf(strStart)); - tempStr=str.substring(str1.length()+1); + String str1 = str.substring(0, str.indexOf(strStart)); + tempStr = str.substring(str1.length() + 1); return tempStr; } @@ -213,11 +241,11 @@ public class ExchangeStringUtil { } // 加33 - public static String addThree(String data){ + public static String addThree(String data) { String result = ""; for (int i = 0; i < data.length() / 2; i++) { - BigInteger a = new BigInteger(data.substring(2*i,2*(i+1)),16); - BigInteger b = new BigInteger("33",16); + BigInteger a = new BigInteger(data.substring(2 * i, 2 * (i + 1)), 16); + BigInteger b = new BigInteger("33", 16); BigInteger c = a.add(b); result = result + ExchangeStringUtil.decToHex(c.toString(10)); } @@ -226,11 +254,11 @@ public class ExchangeStringUtil { } // 减33 - public static String cutThree(String data){ + public static String cutThree(String data) { String result = ""; for (int i = 0; i < data.length() / 2; i++) { - BigInteger a = new BigInteger(data.substring(2*i,2*(i+1)),16); - BigInteger b = new BigInteger("33",16); + BigInteger a = new BigInteger(data.substring(2 * i, 2 * (i + 1)), 16); + BigInteger b = new BigInteger("33", 16); BigInteger c = a.subtract(b); result = result + ExchangeStringUtil.decToHex(c.toString(10)); } @@ -270,16 +298,17 @@ public class ExchangeStringUtil { * @return */ public static String decToHex(String dec) { - BigInteger data = new BigInteger(dec,10); + BigInteger data = new BigInteger(dec, 10); String result = data.toString(16); if (result.length() < 2) { result = "0" + result; } - if ((result.length() % 2)!=0) { + if ((result.length() % 2) != 0) { result = "0" + result; } return result.toUpperCase(); } + /** * 十六进制数据转换为十进制字符串数 * @@ -287,32 +316,32 @@ public class ExchangeStringUtil { * @return */ public static String hexToDec(String hex) { - BigInteger data = new BigInteger(hex,16); + BigInteger data = new BigInteger(hex, 16); return data.toString(10); } - public static String IntToHex(int n){ + public static String IntToHex(int n) { char[] ch = new char[20]; int nIndex = 0; - while ( true ){ - int m = n/16; - int k = n%16; - if ( k == 15 ) + while (true) { + int m = n / 16; + int k = n % 16; + if (k == 15) ch[nIndex] = 'F'; - else if ( k == 14 ) + else if (k == 14) ch[nIndex] = 'E'; - else if ( k == 13 ) + else if (k == 13) ch[nIndex] = 'D'; - else if ( k == 12 ) + else if (k == 12) ch[nIndex] = 'C'; - else if ( k == 11 ) + else if (k == 11) ch[nIndex] = 'B'; - else if ( k == 10 ) + else if (k == 10) ch[nIndex] = 'A'; else - ch[nIndex] = (char)('0' + k); + ch[nIndex] = (char) ('0' + k); nIndex++; - if ( m == 0 ) + if (m == 0) break; n = m; } @@ -338,7 +367,7 @@ public class ExchangeStringUtil { return sbf.toString().trim(); } - public static String bytesToHexString(byte[] src){ + public static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; @@ -356,6 +385,7 @@ public class ExchangeStringUtil { /** * 字符串转化成为16进制字符串 + * * @param s * @return */ @@ -371,6 +401,7 @@ public class ExchangeStringUtil { /** * 字符串转换成为16进制(无需Unicode编码) + * * @param str * @return */ @@ -391,6 +422,7 @@ public class ExchangeStringUtil { /** * 16进制转换成为string类型字符串 + * * @param s * @return */ @@ -417,15 +449,15 @@ public class ExchangeStringUtil { } - /** * 字节转十六进制 + * * @param b 需要进行转换的byte字节 - * @return 转换后的Hex字符串 + * @return 转换后的Hex字符串 */ - public static String byteToHex(byte b){ + public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF); - if(hex.length() < 2){ + if (hex.length() < 2) { hex = "0" + hex; } return hex; @@ -433,24 +465,25 @@ public class ExchangeStringUtil { /** * hex字符串转byte数组 + * * @param inHex 待转换的Hex字符串 - * @return 转换后的byte数组结果 + * @return 转换后的byte数组结果 */ - public static byte[] hexToByteArray(String inHex){ + public static byte[] hexToByteArray(String inHex) { int hexlen = inHex.length(); byte[] result; - if (hexlen % 2 == 1){ + if (hexlen % 2 == 1) { //奇数 hexlen++; - result = new byte[(hexlen/2)]; - inHex="0"+inHex; - }else { + result = new byte[(hexlen / 2)]; + inHex = "0" + inHex; + } else { //偶数 - result = new byte[(hexlen/2)]; + result = new byte[(hexlen / 2)]; } - int j=0; - for (int i = 0; i < hexlen; i+=2){ - result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16); + int j = 0; + for (int i = 0; i < hexlen; i += 2) { + result[j] = (byte) Integer.parseInt(inHex.substring(i, i + 2), 16); j++; } return result; @@ -476,7 +509,7 @@ public class ExchangeStringUtil { String sub = hexString.substring(index, index + 2); - bytes[index/2] = (byte) Integer.parseInt(sub,16); + bytes[index / 2] = (byte) Integer.parseInt(sub, 16); index += 2; } @@ -496,7 +529,7 @@ public class ExchangeStringUtil { /** * 字符串是否为空 - * + *

* 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。 * * @param str @@ -923,9 +956,9 @@ public class ExchangeStringUtil { * @return byte */ public static byte uniteBytes(byte src0, byte src1) { - byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue(); + byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); _b0 = (byte) (_b0 << 4); - byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue(); + byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); byte ret = (byte) (_b0 ^ _b1); return ret; } @@ -973,11 +1006,11 @@ public class ExchangeStringUtil { } //字符转二进制 - public static String toBinary(String str){ - char[] strChar=str.toCharArray(); - String result=""; - for(int i=0;i * 方 法 名: getTodayWeather
* - * @param Cityid - * 城市编码 + * @param Cityid 城市编码 */ public static Map getTodayWeather1(String Cityid) throws IOException, NullPointerException { // 连接中央气象台的API - String url1= "https://free-api.heweather.net/s6/weather/now?location="+Cityid+"&key=3c3fa198cacc4152b94b20def11b2455"; + String url1 = "https://free-api.heweather.net/s6/weather/now?location=" + Cityid + "&key=3c3fa198cacc4152b94b20def11b2455"; URL url = new URL(url1); URLConnection connectionData = url.openConnection(); @@ -1120,29 +1151,29 @@ public class ExchangeStringUtil { sb.append(line); String datas = sb.toString(); //截取[]转化为json格式 - datas = datas.replace(datas.substring(datas.indexOf(":")+1,datas.indexOf(":")+2),""); - datas = datas.replace(datas.substring(datas.length()-2,datas.length()-1),""); + datas = datas.replace(datas.substring(datas.indexOf(":") + 1, datas.indexOf(":") + 2), ""); + datas = datas.replace(datas.substring(datas.length() - 2, datas.length() - 1), ""); JSONObject jsonData = JSONObject.parseObject(datas); JSONObject info = jsonData.getJSONObject("HeWeather6"); JSONObject jsonData1 = JSONObject.parseObject(info.getString("basic").toString()); JSONObject jsonData2 = JSONObject.parseObject(info.getString("update").toString()); JSONObject jsonData3 = JSONObject.parseObject(info.getString("now").toString()); - map.put("location",jsonData1.getString("location").toString()); - map.put("parent_city",jsonData1.getString("parent_city").toString()); - map.put("admin_area",jsonData1.getString("admin_area").toString()); - map.put("cnty",jsonData1.getString("cnty").toString()); + map.put("location", jsonData1.getString("location").toString()); + map.put("parent_city", jsonData1.getString("parent_city").toString()); + map.put("admin_area", jsonData1.getString("admin_area").toString()); + map.put("cnty", jsonData1.getString("cnty").toString()); String time = jsonData2.getString("loc").toString(); String week = strToDate(time); - map.put("week",week); - map.put("time",jsonData2.getString("loc").toString()); + map.put("week", week); + map.put("time", jsonData2.getString("loc").toString()); - map.put("tmp",jsonData3.getString("tmp").toString()); - map.put("wind_dir",jsonData3.getString("wind_dir").toString()); - map.put("cond_txt",jsonData3.getString("cond_txt").toString()); - map.put("cond_code",jsonData3.getString("cond_code").toString()); + map.put("tmp", jsonData3.getString("tmp").toString()); + map.put("wind_dir", jsonData3.getString("wind_dir").toString()); + map.put("cond_txt", jsonData3.getString("cond_txt").toString()); + map.put("cond_code", jsonData3.getString("cond_code").toString()); System.out.println(map); } catch (SocketTimeoutException e) { System.out.println("连接超时"); @@ -1150,7 +1181,7 @@ public class ExchangeStringUtil { System.out.println("加载文件出错"); } catch (ParseException e) { e.printStackTrace(); - }finally { + } finally { //关闭流 // try { // if(br!=null){ @@ -1166,6 +1197,7 @@ public class ExchangeStringUtil { /** * 时间获得星期 + * * @param strDate * @return * @throws ParseException @@ -1178,24 +1210,26 @@ public class ExchangeStringUtil { String week = sdf.format(c.getTime()); return week; } + /** * 字符集转码 + * * @param url * @return * @throws UnsupportedEncodingException */ public static String urlEncode(String url) throws UnsupportedEncodingException { - if(url == null) { + if (url == null) { return null; } final String reserved_char = ";/?:@=&"; String ret = ""; - for(int i=0; i < url.length(); i++) { - String cs = String.valueOf( url.charAt(i) ); - if(reserved_char.contains(cs)){ + for (int i = 0; i < url.length(); i++) { + String cs = String.valueOf(url.charAt(i)); + if (reserved_char.contains(cs)) { ret += cs; - }else{ + } else { ret += URLEncoder.encode(cs, "utf-8"); } } @@ -1206,12 +1240,9 @@ public class ExchangeStringUtil { /** * 判断时间是否在时间段内 * - * @param date - * 当前时间 yyyy-MM-dd HH:mm:ss - * @param strDateBegin - * 开始时间 00:00:00 - * @param strDateEnd - * 结束时间 00:05:00 + * @param date 当前时间 yyyy-MM-dd HH:mm:ss + * @param strDateBegin 开始时间 00:00:00 + * @param strDateEnd 结束时间 00:05:00 * @return */ public static boolean isInDate(Date date, String strDateBegin, @@ -1260,7 +1291,7 @@ public class ExchangeStringUtil { // } if (strDateS >= strDateBeginS && strDateS < strDateEndS) { return true; - }else { + } else { return false; } @@ -1268,43 +1299,44 @@ public class ExchangeStringUtil { /** * 当前时间向推几小时 + * * @param ihour 小时 * @return String */ - public static String dateRoll(int ihour,String curDate) { - try{ + public static String dateRoll(int ihour, String curDate) { + try { DateTimeFormatter df1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //获取当前时间 LocalDateTime date = LocalDateTime.now(); - if (curDate.length()>0){ - date=dateConvertToLocalDateTime(df2.parse(curDate)); + if (curDate.length() > 0) { + date = dateConvertToLocalDateTime(df2.parse(curDate)); } //获取当前时间的前几小时时间 LocalDateTime localDateTime = date.minusHours(ihour); return df1.format(localDateTime); - }catch (Exception e){ + } catch (Exception e) { return ""; } } //获取当前时间前几分钟 - public static String dateTime(int a,String curDate) { - try{ + public static String dateTime(int a, String curDate) { + try { // 设置传入的时间格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String currentTime="";//当前时间 - Calendar cal=Calendar.getInstance(); - if (!curDate.isEmpty()){ + String currentTime = "";//当前时间 + Calendar cal = Calendar.getInstance(); + if (!curDate.isEmpty()) { Date date = df.parse(curDate); cal.setTime(date); } - cal.add(Calendar.MINUTE,-a);// a分钟之前的时间 + cal.add(Calendar.MINUTE, -a);// a分钟之前的时间 //格式化指定形式的时间 - currentTime = df.format(cal.getTime());//获取到完整的时间 - return currentTime; - }catch (Exception e){ - return ""; + currentTime = df.format(cal.getTime());//获取到完整的时间 + return currentTime; + } catch (Exception e) { + return ""; } } diff --git a/user-service/src/test/java/com/mh/user/device/CRC16Test.java b/user-service/src/test/java/com/mh/user/device/CRC16Test.java index ef2ce3d..d4fdf20 100644 --- a/user-service/src/test/java/com/mh/user/device/CRC16Test.java +++ b/user-service/src/test/java/com/mh/user/device/CRC16Test.java @@ -3,6 +3,8 @@ package com.mh.user.device; import com.mh.user.utils.ExchangeStringUtil; import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; /** * @Classname CRC16Test @@ -67,11 +69,37 @@ public class CRC16Test { //测试 public static void main(String[] args) throws IOException { // c0a8020a1f90ff04fb0000000100010200000300000400000500000600000700140800000901cb0a00000b00000c00000d00000e00000f0000100000110025120000130910 - byte[] buffer; - String string = "c0a8020a1f90ff02fd0000000100000200000300000400000500000600000700000800010900000a00780b00010c8c310d00000e00000f0000100000110022120000132d1e140000150000160000170001182c381900001a01a61b00001c00001d00011e00011f25cd20000121b1332200002300002400002500002600712700002834202900002a00002b00002c00002d00402e00002f0363a6ff"; - buffer = ExchangeStringUtil.HexString2Bytes(string); - int crc16 = CRC16Test.calcCrc16(buffer,buffer.length); - System.out.println(String.format("0x%04x", crc16));//0x7c09 +// byte[] buffer; +// String string = "c0a8020a1f90ff02fd0000000100000200000300000400000500000600000700000800010900000a00780b00010c8c310d00000e00000f0000100000110022120000132d1e140000150000160000170001182c381900001a01a61b00001c00001d00011e00011f25cd20000121b1332200002300002400002500002600712700002834202900002a00002b00002c00002d00402e00002f0363a6ff"; +// buffer = ExchangeStringUtil.HexString2Bytes(string); +// int crc16 = CRC16Test.calcCrc16(buffer,buffer.length); +// System.out.println(String.format("0x%04x", crc16));//0x7c09 +// String str; +// str = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("3"), 2) // 设备地址 +// + ExchangeStringUtil.addZeroForNum("3", 2) // 功能码 +// + ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex("0010"), 4) // 寄存器地址 +// + ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(String.valueOf("1")), 4); // 读取寄存器个数 +// // 循环冗余校验 +// String checkWord = ExchangeStringUtil.getStrCRC16(str); //CRC16校验 +// str = str + checkWord; +// System.out.println(str); + String receiveData = "04030202CDB4B1"; + String dataLength = receiveData.substring(4, 6); + int dataLengthInt = Integer.parseInt(dataLength, 16); + // 截取数据域 + String data = receiveData; + data = receiveData.substring(6, 6 + dataLengthInt * 2); + System.out.println(data); + String sValue = ExchangeStringUtil.hexToDec(data); + System.out.println(ExchangeStringUtil.hexToDec(data)); + System.out.println(ExchangeStringUtil.rightAddZeroForNum("1", 2+1)); + BigDecimal test1 = new BigDecimal(ExchangeStringUtil.rightAddZeroForNum("1", 2+1)); + System.out.println(test1); + sValue = (new BigDecimal(sValue)).divide(test1, 2, RoundingMode.HALF_UP).toString(); + System.out.println(sValue); + String test = String.valueOf(Math.abs(ExchangeStringUtil.hexToSingle(data))); + System.out.println(test); + } }