| | |
| | | package com.mes.device; |
| | | |
| | | import com.github.xingshuangs.iot.utils.IntegerUtil; |
| | | import com.github.xingshuangs.iot.utils.ShortUtil; |
| | | |
| | | import java.lang.reflect.Array; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.util.*; |
| | |
| | | Array.setByte(valueList, i, plcValueArray[plcParameterInfo.getAddressIndex() + i]); |
| | | } |
| | | if (plcParameterInfo.getAddressLength() == 2) { |
| | | plcParameterInfo.setValue(String.valueOf(byte2short(valueList))); |
| | | plcParameterInfo.setValue(String.valueOf(ShortUtil.toUInt16(valueList))); |
| | | } else if (plcParameterInfo.getAddressLength() == 4) { |
| | | plcParameterInfo.setValue(String.valueOf(byte2int(valueList))); |
| | | plcParameterInfo.setValue(String.valueOf(IntegerUtil.toUInt32(valueList))); |
| | | } |
| | | else if (plcParameterInfo.getAddressLength() >10) { |
| | | plcParameterInfo.setValue((byteToHexString(valueList))); |
| | | } else { |
| | | String valuestr = new String(valueList); |
| | | plcParameterInfo.setValue(valuestr); |
| | | plcParameterInfo.setValue((byteToHexString(valueList))); |
| | | } |
| | | } |
| | | } |
| | |
| | | } |
| | | }*/ |
| | | } |
| | | /** |
| | | * 把写入值转化为byte[] |
| | | * @param param 参数实例 |
| | | * @param data 写入值的字符类型 |
| | | */ |
| | | public byte[] setValueToBytes(PlcParameterInfo param, String data) { |
| | | if (param.getAddressLength() == 2) { |
| | | return ShortUtil.toByteArray(Integer.parseInt(data)); |
| | | |
| | | } else if (param.getAddressLength() == 4) { |
| | | |
| | | return IntegerUtil.toByteArray(Long.parseLong(data)); |
| | | } |
| | | else if (param.getAddressLength() >10) { |
| | | return data.getBytes(); |
| | | } else { |
| | | return data.getBytes(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * short类型转byte[] |
| | |
| | | public static byte[] short2byte(short s) { |
| | | byte[] b = new byte[2]; |
| | | for (int i = 0; i < 2; i++) { |
| | | int offset = 16 - (i + 1) * 8; //因为byte占4个字节,所以要计算偏移量 |
| | | int offset = 16 - (i + 1) * 8; //计算偏移量 |
| | | b[i] = (byte) ((s >> offset) & 0xff); //把16位分为2个8位进行分别存储 |
| | | } |
| | | return b; |
| | |
| | | * |
| | | * @param b byte[]类型值 |
| | | */ |
| | | public static short byte2int(byte[] b) { |
| | | short l = 0; |
| | | public static int byte2int(byte[] b) { |
| | | int l = 0; |
| | | for (int i = 0; i < 4; i++) { |
| | | l <<= 8; //<<=和我们的 +=是一样的,意思就是 l = l << 8 |
| | | l |= (b[3-i] & 0xff); //和上面也是一样的 l = l | (b[i]&0xff) |
| | | } |
| | | return l; |
| | | } |
| | | public static byte[] int2byte(int s){ |
| | | byte[] b = new byte[2]; |
| | | for(int i = 0; i < 4; i++){ |
| | | int offset = 16 - (i+1)*8; //因为byte占4个字节,所以要计算偏移量 |
| | | b[i] = (byte)((s >> offset)&0xff); //把32位分为4个8位进行分别存储 |
| | | } |
| | | return b; |
| | | } |
| | | public static String byteToHexString(byte[] bytes) { |
| | | String str = new String(bytes, StandardCharsets.UTF_8).trim(); |
| | | return str; |