Commit f94620d2 authored by 耿迪迪's avatar 耿迪迪

接受设备上报数据 gengdidi

parent a97ee239
......@@ -10,12 +10,10 @@ public class ReciveReportData {
/** 设备编号*/
private String deviceCode;
/** 设备状态*/
private String deviceStatus;
private String alarmType;
/** 设备浓度*/
private BigDecimal potency;
private BigDecimal pressure;
/** 设备类型*/
private String deviceType;
private String DeviceDescribe;
}
package com.zehong.gassdevicereport.netty;
import com.zehong.gassdevicereport.entity.TDeviceReportData;
import com.zehong.gassdevicereport.utils.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DecryptReportedData {
private Logger logger = LoggerFactory.getLogger(DecryptReportedData.class);
private String reportedDataStr;
private String deviceType;
public DecryptReportedData(String reportedDataStr,String deviceType) {
this.reportedDataStr = reportedDataStr;
this.deviceType = deviceType;
}
public TDeviceReportData getReportedData(){
try {
TDeviceReportData tDeviceReportData = new TDeviceReportData();
//设备编号
tDeviceReportData.setDeviceNum(getDeviceNum());
//设备上报时间
Date reportedTime = getReportedTime();
tDeviceReportData.setReportTime(reportedTime);
// 标况累计量
double standardConditionAccumulation = HexUtils.hexToDouble(reportedDataStr.substring(48, 64));
tDeviceReportData.setStandardConditionAccumulation(new BigDecimal(standardConditionAccumulation));
// 工况累计量
double workingConditionAccumulation = HexUtils.hexToDouble(reportedDataStr.substring(64, 80));
tDeviceReportData.setWorkingConditionAccumulation(new BigDecimal(workingConditionAccumulation));
// 标况流量
float standardConditionFlow = HexUtils.hexToFloat(reportedDataStr.substring(80, 88));
tDeviceReportData.setStandardConditionFlow(new BigDecimal(standardConditionFlow));
// 工况流量
float workingConditionFlow = HexUtils.hexToFloat(reportedDataStr.substring(88, 96));
tDeviceReportData.setWorkingConditionFlow(new BigDecimal(workingConditionFlow));
// 温度
float temperature = HexUtils.hexToFloat(reportedDataStr.substring(96, 104));
tDeviceReportData.setTemperature(new BigDecimal(temperature));
// 压力
float pressure = HexUtils.hexToFloat(reportedDataStr.substring(104, 112));
tDeviceReportData.setPressure(new BigDecimal(pressure));
//通讯字段
String communicationStatus = getCommunicationStatus();
tDeviceReportData.setCommunicationStatus(communicationStatus);
//设备状态
String deviceStatus = getDeviceStatus();
tDeviceReportData.setDeviceStatus(deviceStatus);
return tDeviceReportData;
} catch (Exception e) {
logger.error("上报数据组装数据报错!"+e);
}
return null;
}
/**
* 获取设备编号
* @return
*/
private String getDeviceNum(){
String deviceNum = reportedDataStr.substring(0,36);
StringBuilder deviceNumStr = new StringBuilder("");
for(int i = 0; i < deviceNum.length(); i+=2){
String code = deviceNum.substring(i,i+2);
byte codeByte = HexUtils.hexToByte(code);
deviceNumStr.append(codeByte);
}
return deviceNum.toString();
}
/**
* 获取上报时间
* @return
* @throws ParseException
*/
private Date getReportedTime() throws ParseException {
String reportTime = reportedDataStr.substring(36,48);
StringBuilder timeStr = new StringBuilder("");
timeStr.append(reportTime.substring(0,2));
timeStr.append("-");
timeStr.append(reportTime.substring(2,4));
timeStr.append("-");
timeStr.append(reportTime.substring(4,6));
timeStr.append(" ");
timeStr.append(reportTime.substring(6,8));
timeStr.append(":");
timeStr.append(reportTime.substring(8,10));
timeStr.append(":");
timeStr.append(reportTime.substring(10,12));
return new SimpleDateFormat("yy-MM-dd HH:mm:ss").parse(timeStr.toString());
}
/**
* 通讯字
* @return
*/
private String getCommunicationStatus(){
String communicationStatus = reportedDataStr.substring(112, 116);
StringBuilder communicationStatusStr = new StringBuilder("");
communicationStatusStr.append( HexUtils.hexToByte(communicationStatus.substring(0,2)));
communicationStatusStr.append( HexUtils.hexToByte(communicationStatus.substring(2,4)));
return communicationStatus.toString();
}
/**
* 设备状态字段 16进制转为二进制 高位或地位不足8位时左边补0
* @return
*/
private String getDeviceStatus(){
String deviceStatus = reportedDataStr.substring(116, 120);
String lowPosition = HexUtils.hexToBinary(deviceStatus.substring(0,2));
String heightPosition = HexUtils.hexToBinary(deviceStatus.substring(2,4));
return deviceType+lowPosition+heightPosition;
}
}
package com.zehong.gassdevicereport.netty;
import com.alibaba.fastjson.JSONObject;
import com.zehong.gassdevicereport.constant.Constant;
import com.zehong.gassdevicereport.entity.ReciveReportData;
import com.zehong.gassdevicereport.entity.TDeviceReportData;
import com.zehong.gassdevicereport.service.ITDeviceReportDataService;
import com.zehong.gassdevicereport.utils.CrcUtil;
import com.zehong.gassdevicereport.utils.HexUtils;
import com.zehong.gassdevicereport.utils.RedisUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
......@@ -18,7 +19,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
/**
......@@ -36,6 +36,10 @@ public class ServerHandler extends ChannelInboundHandlerAdapter {
@Autowired
private ITDeviceReportDataService itDeviceReportDataService;
private final static String METER = "4";
private final static String METER_ALARM = "1";
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
......@@ -66,35 +70,41 @@ public class ServerHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException{
//msg为接收到的客户端传递的数据 个人这边直接传的json 数据
ByteBuf readMessage= (ByteBuf) msg;
//解析客户端json 数据
String a = readMessage.toString(CharsetUtil.UTF_8);
ReciveReportData reciveReportData = JSONObject.parseObject(a,ReciveReportData.class);
System.out.println("接收到的数据"+readMessage.toString(CharsetUtil.UTF_8));
String msgStr = readMessage.toString(CharsetUtil.UTF_8);
if(msgStr.length() != 124){
return;
}
byte[] bytes = HexUtils.hexToByteArray( msgStr.substring(0,msgStr.length()-4));
String checkVule = CrcUtil.getCrcToHex(bytes,true);
String checkCode = msgStr.substring(msgStr.length()-4,msgStr.length());
if(!checkVule.equals(checkCode)){
return;
}
//设备请求的 服务器端的地址 用作监听设备请求的那个端口
SocketChannel channel=(SocketChannel)ctx.channel();
int port = channel.localAddress().getPort();
TDeviceReportData tDeviceReportData = new TDeviceReportData();
if(7397 == port){
reciveReportData.setDeviceType("4");
reciveReportData.setDeviceDescribe("压力异常");
redisUtil.set(Constant.DEVICE_REDIS_KEY+reciveReportData.getDeviceCode(),reciveReportData);
tDeviceReportData = new DecryptReportedData(msgStr,"nacangEVC300").getReportedData();
}else{
redisUtil.set(Constant.DEVICE_REDIS_KEY+reciveReportData.getDeviceCode(),reciveReportData);
}
//更新redis中设备最新信息
//TDeviceReportData tDeviceReportData = new TDeviceReportData();
tDeviceReportData = new DecryptReportedData(msgStr,"tianxinCPUcard").getReportedData();
}
//缓存设备信息
ReciveReportData reciveReportData = new ReciveReportData();
reciveReportData.setDeviceCode(tDeviceReportData.getDeviceNum());
reciveReportData.setDeviceType(METER);
reciveReportData.setAlarmType(METER_ALARM);
reciveReportData.setPressure(tDeviceReportData.getPressure());
redisUtil.set(Constant.DEVICE_REDIS_KEY + reciveReportData.getDeviceCode(),tDeviceReportData);
//设备上报数据入库
// itDeviceReportDataService.insertTDeviceReportData(tDeviceReportData);
itDeviceReportDataService.insertTDeviceReportData(tDeviceReportData);
//判断端口如果客户端请求的端口号为9898 就是写入第一张表 这样可以实现 设备传递数据参数不一致
String rmsg="0";//返回失败的信息
/* String rmsg="0";//返回失败的信息
ByteBuf message= Unpooled.copiedBuffer(rmsg.getBytes());//处理返回的信息
//ctx.write(in2);//返回信息
ctx.writeAndFlush(message);//返回信息
//刷新缓存区
ctx.flush();
ctx.flush();*/
}
@Override
......
......@@ -41,9 +41,8 @@ public class DealWithAndSendRecevieDataTask implements ScheduledOfTask {
@Value("${webSocektUrl}")
private String webSocektUrl;
@Autowired
private ISysDictTypeService iSysDictTypeService;
private final static String PIPE = "O";
private final static String PIPE_ALARMTYPE = "0";
@Override
public void execute() {
......@@ -66,10 +65,9 @@ public class DealWithAndSendRecevieDataTask implements ScheduledOfTask {
insertAlarmInfo(monitorDevice.getRelationDeviceId(),monitorDevice.getRelationDeviceThreshold(), relationDeviceInfo);
//关联管道
ReciveReportData pipe = new ReciveReportData();
pipe.setPotency(deviceInfo.getPotency().subtract(relationDeviceInfo.getPotency()));
pipe.setDeviceType("0");
pipe.setDeviceStatus("1");
pipe.setDeviceDescribe(iSysDictTypeService.selectDictDataByType("t_alarm_pipe_describe").get(0).getDictLabel());
pipe.setPressure(deviceInfo.getPressure().subtract(relationDeviceInfo.getPressure()));
pipe.setDeviceType(PIPE);
pipe.setAlarmType(PIPE_ALARMTYPE);
insertAlarmInfo(monitorDevice.getRelationPipeId(),monitorDevice.getRelationPipeThreshold(),pipe);
}
}
......@@ -86,7 +84,7 @@ public class DealWithAndSendRecevieDataTask implements ScheduledOfTask {
private void insertAlarmInfo(Long deviceId,BigDecimal deviceThreshold, ReciveReportData deviceInfo) {
TDeviceAlarm alarm = itDeviceAlarmService.selectTDeviceAlarmByDeviceId(deviceId);
//比较设备上报信息及阈值信息
if(deviceThreshold.compareTo(deviceInfo.getPotency()) == -1){
if(deviceThreshold.compareTo(deviceInfo.getPressure()) == -1){
//判断报警表中是否有该设备报警信息:无新增报警信息、有更新报警信息
if(null != alarm){
//TODO 添加更新字段
......@@ -95,10 +93,10 @@ public class DealWithAndSendRecevieDataTask implements ScheduledOfTask {
}else{
TDeviceAlarm alarmInsert = new TDeviceAlarm();
alarmInsert.setDeviceId(deviceId);
alarmInsert.setAlarmType(deviceInfo.getDeviceStatus());
alarmInsert.setAlarmType(deviceInfo.getAlarmType());
alarmInsert.setDeviceType(deviceInfo.getDeviceType());
alarmInsert.setStartTime(new Date());
alarmInsert.setAlarmValue(deviceInfo.getDeviceDescribe());
alarmInsert.setAlarmValue(deviceInfo.getPressure().toString());
itDeviceAlarmService.insertTDeviceAlarm(alarmInsert);
pushWedSocket(alarmInsert.getAlarmId());
......
package com.zehong.gassdevicereport.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CrcUtil {
/**
* 计算CRC16校验码
* @param bytes
* @return
*/
public static int getCRC(byte[] bytes) {
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;
}
}
}
return CRC;
}
public static String getCrcToHex(byte[] bytes) {
return Integer.toHexString(getCRC(bytes));
}
/**
* 计算CRC16校验码
* @param bytes
* @param reverse 是否转换高低位
* @return
*/
public static String getCrcToHex(byte[] bytes,boolean reverse) {
int CRC = getCRC(bytes);
//高低位转换,看情况使用(譬如本人这次对led彩屏的通讯开发就规定校验码高位在前低位在后,也就不需要转换高低位)
if(reverse){
CRC = ( (CRC & 0x0000FF00) >> 8) | ( (CRC & 0x000000FF ) << 8);
}
return Integer.toHexString(CRC);
}
public static void main(String[] args) {
//字符串转16进制byte数组
String str16 = "0806040303030004040803070309010002032108271532404136cb5fdbd2b0004132f1e60000000042ef193b42d3cd6742012c5242edf73a0000000080a6";
/* byte[] bytes = HexUtils.hexToByteArray(str16);
// byte[] bytes = str16.getBytes();
System.out.println("str16:" + str16);
System.out.println(getCrcToHex(bytes,true));
System.out.println("str16:" + str16.substring(0,str16.length()-4));
System.out.println(str16.substring(str16.length()-4,str16.length()));*/
//System.out.println(HexUtils.hexToByte(str16.substring(0,36)));
System.out.println(Integer.parseInt(str16.substring(0,36),16));
}
}
package com.zehong.gassdevicereport.utils;
public class HexUtils {
/**
* 字节转十六进制
* @param b 需要进行转换的byte字节
* @return 转换后的Hex字符串
*/
public static String byteToHex(byte b){
String hex = Integer.toHexString(b & 0xFF);
if(hex.length() < 2){
hex = "0" + hex;
}
return hex;
}
/**
* 字节数组转16进制
* @param bytes 需要转换的byte数组
* @return 转换后的Hex字符串
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
/**
* Hex字符串转byte
* @param inHex 待转换的Hex字符串
* @return 转换后的byte
*/
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
/**
* hex字符串转byte数组
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
/**
* 十六进制转单浮点
* @param hex
* @return
*/
public static float hexToFloat(String hex){
Integer i = Integer.valueOf(hex.trim(), 16);
return Float.intBitsToFloat(i);
}
/**
* 十六进制转浮点
* @param hex
* @return
*/
public static double hexToDouble(String hex){
Long l = Long.valueOf(hex,16).longValue();
return Double.longBitsToDouble(l);
}
/**
* 十六进制转二进制
* @param hex
* @return
*/
public static String hexToBinary(String hex){
Integer num = Integer.parseInt(hex,16);
return Integer.toBinaryString(num);
}
}
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