package com.gzlh.device.plc.client; import com.gzlh.config.ModuleEnum; import com.gzlh.device.plc.handler.PLCHadnler; import com.gzlh.utils.DeviceCache; import com.gzlh.utils.ModbusUtils; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @Slf4j @ChannelHandler.Sharable public class PlcClientHandler extends SimpleChannelInboundHandler { private PlcNettyConfig ledNettyConfig; @Autowired private PLCHadnler plcHadnler; public PlcClientHandler(PlcNettyConfig ledNettyConfig) { this.ledNettyConfig = ledNettyConfig; } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // log.info("PLC 客户端收到消息:" + msg); // 修改设备状态信息 DeviceCache.changeDeviceStatus(ModuleEnum.PLC_MODULE.getModuleEn(),1); // String crc = msg.substring(msg.length() - 4 ); String data = msg.substring(0, msg.length() - 4); String str = ModbusUtils.buildRequestPacket(data); if (msg.equalsIgnoreCase(str)){ plcHadnler.handlerMsg(msg); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.error("PLC 客户端 连接断开,进行重连"); // 断连设备状态设为0 DeviceCache.changeDeviceStatus(ModuleEnum.PLC_MODULE.getModuleEn(),0); ledNettyConfig.connect(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }