package com.mes.util; import com.github.s7connector.api.DaveArea; import com.github.s7connector.api.S7Connector; import com.github.xingshuangs.iot.protocol.s7.service.S7PLC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.text.DecimalFormat; public class S7Util { public static final Logger log = LoggerFactory.getLogger(S7Util.class); public static Boolean getFswAlarm(S7Connector s7Connector){ byte[] bytes1 = s7Connector.read(DaveArea.DB, 9051, 1, 24); int alarm242 = getBit(bytes1[0],5); if(alarm242 == 1){ return false; } int alarm243 = getBit(bytes1[0],4); if(alarm243 == 1){ return false; } int alarm244 = getBit(bytes1[0],3); if(alarm244 == 1){ return false; } int alarm245 = getBit(bytes1[0],2); if(alarm245 == 1){ return false; } int alarm246 = getBit(bytes1[0],1); if(alarm246 == 1){ return false; } int alarm247 = getBit(bytes1[0],0); if(alarm247 == 1){ return false; } byte[] bytes2 = s7Connector.read(DaveArea.DB, 9051, 1, 25); int alarm250 = getBit(bytes2[0],7); if(alarm250 == 1){ return false; } int alarm251 = getBit(bytes2[0],6); if(alarm251 == 1){ return false; } int alarm252 = getBit(bytes2[0],5); if(alarm252 == 1){ return false; } int alarm253 = getBit(bytes2[0],4); if(alarm253 == 1){ return false; } int alarm254 = getBit(bytes2[0],3); if(alarm254 == 1){ return false; } int alarm255 = getBit(bytes2[0],2); if(alarm255 == 1){ return false; } int alarm256 = getBit(bytes2[0],1); if(alarm256 == 1){ return false; } return true; } // 格式化s7取出的值 public static String formatS7Val(byte[] val){ int intValue = new BigInteger(xtob(val)).intValue(); float floatValue = Float.intBitsToFloat(intValue); // 保留1位小数 DecimalFormat df = new DecimalFormat("#.#"); df.setMaximumFractionDigits(1); String result = df.format(floatValue); float roundedNum = Float.parseFloat(result); return roundedNum+""; } // 转大端排序 private static byte[] xtob( byte[] bytes){ return bytes; // // 创建新的byte数组并复制原始数据 // byte[] reversedBytes = new byte[bytes.length]; // System.arraycopy(bytes, 0, reversedBytes, 0, bytes.length); // // // 反转byte数组元素的位置 // for (int i = 0; i < bytes.length / 2; i++) { // byte temp = reversedBytes[i]; // reversedBytes[i] = reversedBytes[reversedBytes.length - 1 - i]; // reversedBytes[reversedBytes.length - 1 - i] = temp; // } // return reversedBytes; } private static String byteToBinaryString(byte[] byteArray) { StringBuilder binaryString = new StringBuilder(); for (byte b : byteArray) { binaryString.append(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0')); } return binaryString.toString(); } public static int getBit(byte b, int n) { // 将byte转换为二进制字符串 String binaryString = Integer.toBinaryString(b & 0xFF); // 补足位数到8位 binaryString = String.format("%8s", binaryString).replace(' ', '0'); // 获取第n位的字符,然后转换为整数 return binaryString.charAt(n) == '1' ? 1 : 0; } public static Integer formatS7Int(byte[] val){ return new BigInteger(xtob(val)).intValue(); } }