作者 钟来

投料机状态展示异常

... ... @@ -5,10 +5,13 @@ import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.ByteUtil;
import com.ruoyi.common.utils.GsonConstructor;
import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.config.ScheduledConfig;
import com.zhonglai.luhui.smart.feeder.dto.*;
import com.zhonglai.luhui.smart.feeder.dto.commd.FeederCommd03Request;
import com.zhonglai.luhui.smart.feeder.dto.commd.FeederCommdDto;
import com.zhonglai.luhui.smart.feeder.dto.commd.FeederTimer;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.CmdDto;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.Condata;
... ... @@ -24,6 +27,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 数据监听服务
... ... @@ -40,6 +45,17 @@ public class DateListenService {
this.serialPortService = serialPortService;
}
public static void main(String[] args) {
ConfigurationParameterService.initConfigurationParameter();
String str = "01032E00010004FFE0000000000001000000000000000000000000000000010001000600070000001500000000000000001EC4";
byte[] bytes = ByteUtil.hexStringToByte(str.replaceAll(" ",""));
FeederCommdDto commdDto = new FeederCommdDto(bytes);
AnalysisDataService analysisDataService = new AnalysisDataService();
Map<String,Object> data = analysisDataService.analysis(commdDto);
System.out.println(data);
}
public void run()
{
logger.info("数据上报");
... ... @@ -47,6 +63,7 @@ public class DateListenService {
ScheduledConfig.scheduler.scheduleWithFixedDelay(() -> {
ModbusDto modbusDto = serialPortService.sendHexData(FeederCommdUtil.readAll());
Map<String,Object> data = analysisDataService.analysis(modbusDto);
logger.info("查询投料机所有参数返回的数据:{}",data);
if(null != data && data.size() != 0)
{
Condata condata = BeanUtil.mapToBean(data, Condata.class,false,null);
... ... @@ -62,25 +79,6 @@ public class DateListenService {
}
OperatingData.feederData.setInfo(info);
//投料机不可以读
// List<Integer[]> timerList = new ArrayList<>();
// for(String key:data.keySet())
// {
// if(key.startsWith("timer"))
// {
// FeederTimer feederTimer = (FeederTimer) data.get(key);
// timerList.add(new Integer[]{feederTimer.getTimer_start_h(),feederTimer.getTimer_start_m(),feederTimer.getTimer_close_h(),feederTimer.getTimer_start_m(),feederTimer.getTimer_if_start()});
// }
// }
//
// if(null != timerList && timerList.size() != 0)
// {
// if(ObjectUtil.notEqual(OperatingData.feederConfig.getTimer(),timerList))
// {
// OperatingData.feederConfig.setTimer(timerList);
// reportTimer();
// }
// }
}
},1,10, TimeUnit.SECONDS);
... ... @@ -115,6 +113,7 @@ public class DateListenService {
//上报参数
ScheduledConfig.scheduler.schedule(() -> {
logger.info("内存数据--->{}",OperatingData.feederConfig.getCondata());
try {
Thread.sleep(10000);
reportSerialPortConfig();
... ... @@ -161,27 +160,9 @@ public class DateListenService {
devicedatRequest.setBattlevel(4);
devicedatRequest.setCondata(OperatingData.feederConfig.getCondata());
String str = GsonConstructor.get().toJson(devicedatRequest);
System.out.println(str);
CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject( GsonConstructor.get().fromJson( str, JsonObject.class));
MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
}
// /**
// * 上报投料机定时参数
// */
// public void reportTimer()
// {
// DevicedatRequest devicedatRequest = new DevicedatRequest();
// devicedatRequest.setCmd("devicedata");
// devicedatRequest.setType("4G.hs");
// devicedatRequest.setSignal(4);
// devicedatRequest.setMachstate(1);
// devicedatRequest.setBattlevel(4);
// devicedatRequest.setTimer(OperatingData.feederConfig.getTimer());
// String str = GsonConstructor.get().toJson(devicedatRequest);
// System.out.println(str);
// CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject( GsonConstructor.get().fromJson( str, JsonObject.class));
// MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
// }
/**
* 上报串口参数
... ... @@ -196,7 +177,6 @@ public class DateListenService {
devicedatRequest.setBattlevel(4);
devicedatRequest.setSerialPortConfig(OperatingData.feederConfig.getSerialPortConfig());
String str = GsonConstructor.get().toJson(devicedatRequest);
System.out.println(str);
CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject( GsonConstructor.get().fromJson( str, JsonObject.class));
MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
}
... ... @@ -214,7 +194,6 @@ public class DateListenService {
devicedatRequest.setBattlevel(4);
devicedatRequest.setSysConfig(OperatingData.sysConfig);
String str = GsonConstructor.get().toJson(devicedatRequest);
System.out.println(str);
CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject( GsonConstructor.get().fromJson( str, JsonObject.class));
MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
}
... ... @@ -233,7 +212,6 @@ public class DateListenService {
devicedatRequest.setBattlevel(4);
devicedatRequest.setCameraConfig(OperatingData.cameraConfig);
String str = GsonConstructor.get().toJson(devicedatRequest);
System.out.println(str);
CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject( GsonConstructor.get().fromJson( str, JsonObject.class));
MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
... ... @@ -260,25 +238,4 @@ public class DateListenService {
}
}
public static void main(String[] args) {
ConfigurationParameterService.initConfigurationParameter();
DevicedatRequest devicedatRequest = new DevicedatRequest();
devicedatRequest.setCmd("devicedata");
devicedatRequest.setType("4G.hs");
devicedatRequest.setSignal(4);
devicedatRequest.setMachstate(1);
devicedatRequest.setBattlevel(4);
devicedatRequest.setCondata(OperatingData.feederConfig.getCondata());
devicedatRequest.setInfo(OperatingData.feederData.getInfo());
// devicedatRequest.setTimer(OperatingData.feederConfig.getTimer());
devicedatRequest.setSysConfig(OperatingData.sysConfig);
devicedatRequest.setCameraData(OperatingData.cameraData);
devicedatRequest.setCameraConfig(OperatingData.cameraConfig);
devicedatRequest.setSerialPortConfig(OperatingData.feederConfig.getSerialPortConfig());
System.out.println(GsonConstructor.get().toJson(devicedatRequest));
}
}
... ...
... ... @@ -5,13 +5,12 @@ import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.config.ScheduledConfig;
import com.zhonglai.luhui.smart.feeder.dto.*;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.Condata;
import com.zhonglai.luhui.smart.feeder.service.device.SerialPortService;
import com.zhonglai.luhui.smart.feeder.util.FeederCommd06ResponseType;
import com.zhonglai.luhui.smart.feeder.util.FeederCommdUtil;
import com.zhonglai.luhui.smart.spare.feeder.service.SerialPortService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
... ...
package com.zhonglai.luhui.smart.feeder.service;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.GsonConstructor;
import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.CmdDto;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.DevicedatRequest;
import com.zhonglai.luhui.smart.feeder.service.device.CameraHandle;
import com.zhonglai.luhui.smart.feeder.service.device.handle.CameraRtspHandle;
import com.zhonglai.luhui.smart.feeder.util.MessageUtil;
import com.zhonglai.luhui.smart.spare.feeder.service.NettyClient;
import com.zhonglai.luhui.smart.spare.feeder.service.SerialPortService;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class InitService {
public static SerialPortService serialPortService;
... ... @@ -49,6 +51,8 @@ public class InitService {
nettyClient = new NettyClient(OperatingData.sysConfig.getNettyConfig().getHost(), OperatingData.sysConfig.getNettyConfig().getPort());
nettyClient.start();
jiaozhun();
/**
* 初始化海康的摄像头
*/
... ... @@ -73,4 +77,21 @@ public class InitService {
mqttService.start();
}
private static void jiaozhun()
{
DevicedatRequest devicedatRequest = new DevicedatRequest();
devicedatRequest.setCmd("get_config");
devicedatRequest.setType("4G.hs");
devicedatRequest.setSignal(4);
devicedatRequest.setMachstate(1);
devicedatRequest.setBattlevel(4);
String str = GsonConstructor.get().toJson(devicedatRequest);
JsonObject jsonObject = GsonConstructor.get().fromJson( str, JsonObject.class);
jsonObject.addProperty("configType","timer");
CmdDto cmdDto = new CmdDto().setImei(OperatingData.sysConfig.getNettyConfig().getClientId()).setJsonObject(jsonObject);
System.out.println("发送较准指令:"+cmdDto.generateCmd());
MessageUtil.sendMessage(InitService.nettyClient.getCtx(), cmdDto.generateCmd(),true);
}
}
... ...
package com.zhonglai.luhui.smart.feeder.service.device;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.ruoyi.common.utils.ByteUtil;
import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.config.ScheduledConfig;
import com.zhonglai.luhui.smart.feeder.dto.ModbusDto;
import com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig;
import com.zhonglai.luhui.smart.feeder.dto.commd.FeederCommdDto;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.Condata;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.Info;
import com.zhonglai.luhui.smart.feeder.service.AnalysisDataService;
import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
import com.zhonglai.luhui.smart.feeder.service.InitService;
import com.zhonglai.luhui.smart.feeder.util.FeederCommdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class SerialPortService {
private static final Logger logger = LoggerFactory.getLogger(SerialPortService.class);
private SerialPort serialPort;
// 锁对象
private final Object lock = new Object();
// 用于存储串口返回的数据,使用线程安全的队列
private BlockingQueue<ModbusDto> dataQueue = new LinkedBlockingQueue<>();
private AnalysisDataService analysisDataService = new AnalysisDataService();
public SerialPortService()
{
open();
ModbusDto modbusDto = sendHexData(FeederCommdUtil.readAll());
Map<String,Object> data = analysisDataService.analysis(modbusDto);
if(null != data && data.size() != 0)
{
Condata condata = BeanUtil.mapToBean(data, Condata.class,false,null);
if(condata.getRunstate()==0)
{
condata.setRunstate(3);
}
Info info = BeanUtil.mapToBean(data, Info.class,false,null);
if(ObjectUtil.notEqual(OperatingData.feederConfig.getCondata(),condata))
{
OperatingData.feederConfig.setCondata(condata);
}
OperatingData.feederData.setInfo(info);
}
logger.info("端口启动情况:{}",serialPort.isOpen());
}
private SerialPort findSerialPort()
{
SerialPort serialPort = null;
SerialPort[] serialPorts = SerialPort.getCommPorts();//查找所有串口
for(SerialPort port:serialPorts){
logger.info("Port:{},PortDesc:{},PortDesc:{}",port.getSystemPortName(),port.getPortDescription(),port.getDescriptivePortName());//打印串口名称,如COM4;打印串口类型,如USB Serial;打印串口的完整类型,如USB-SERIAL CH340(COM4)
if(port.getSystemPortName().indexOf("ttyS0")>=0)
{
serialPort = port;
break;
}
}
return serialPort;
}
private void setComPortParameters()
{
SerialPortConfig serialPortConfig = OperatingData.feederConfig.getSerialPortConfig();
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);//设置串口的控制流,可以设置为disabled,或者CTS, RTS/CTS, DSR, DTR/DSR, Xon, Xoff, Xon/Xoff等
serialPort.setComPortParameters(serialPortConfig.getBaudrate(), serialPortConfig.getDataBits(), serialPortConfig.getStopBits(), serialPortConfig.getParity());//一次性设置所有的串口参数,第一个参数为波特率,默认9600;第二个参数为每一位的大小,默认8,可以输入5到8之间的值;第三个参数为停止位大小,只接受内置常量,可以选择(ONE_STOP_BIT, ONE_POINT_FIVE_STOP_BITS, TWO_STOP_BITS);第四位为校验位,同样只接受内置常量,可以选择 NO_PARITY, EVEN_PARITY, ODD_PARITY, MARK_PARITY,SPACE_PARITY。
}
public boolean isOpen()
{
if(null != serialPort && serialPort.isOpen())
{
return true;
}
return false;
}
public boolean open()
{
if(null == serialPort || !serialPort.isOpen())
{
serialPort = findSerialPort();
if(null != serialPort)
{
setComPortParameters();
}
}
if(null == serialPort)
{
logger.error("没有找到串口");
return false;
}
if(!serialPort.isOpen()){
boolean isCommOpeded = serialPort.openPort();//判断串口是否打开,如果没打开,就打开串口。打开串口的函数会返回一个boolean值,用于表明串口是否成功打开了
addLister();
return isCommOpeded;
}
return true;
}
private void addLister()
{
if(serialPort.isOpen()){
serialPort.addDataListener(new SerialPortDataListener() {//添加监听器。由于该监听器有两个函数,无法使用Lambda表达式
@Override
public int getListeningEvents() {
// TODO Auto-generated method stub
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;//返回要监听的事件类型,以供回调函数使用。可发回的事件包括:SerialPort.LISTENING_EVENT_DATA_AVAILABLE,SerialPort.LISTENING_EVENT_DATA_WRITTEN,SerialPort.LISTENING_EVENT_DATA_RECEIVED。分别对应有数据在串口(不论是读的还是写的),有数据写入串口,从串口读取数据。如果AVAILABLE和RECEIVED同时被监听,优先触发RECEIVED
}
@Override
public void serialEvent(SerialPortEvent event) {//事件处理函数
// TODO Auto-generated method stub
String data = "";
if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
return;//判断事件的类型
}
SerialPort port = event.getSerialPort();
try {
Thread.sleep(500);
byte[] bytes = readFromPort(port);
logger.info("串口返回数据:"+ByteUtil.toHexString(bytes));
FeederCommdDto commdDto = new FeederCommdDto(bytes);
dataQueue.offer(commdDto); // 将数据添加到队列中// 处理串口返回的数据
} catch (Exception e) {
logger.error("返回数据处理异常",e);
}
}
});
}
}
public boolean close()
{
dataQueue.clear();
if(null != serialPort)
{
return serialPort.closePort();//关闭串口。该函数同样会返回一个boolean值,表明串口是否成功关闭
}
return true;
}
/**
* 发送16进制数据
* @param hexStr
* @throws IOException
*/
public ModbusDto sendHexData(String hexStr) {
logger.info("串口写入:{}",hexStr);
byte[] bytes = ByteUtil.hexStringToByte(hexStr.replace(" ","").trim().toUpperCase());
return sendByte(bytes);
}
// /**
// * 发送支持中文的字符串
// * @param str
// * @throws IOException
// */
// public ModbusDto sendStrData(String str) {
// return sendByte(str.getBytes(StandardCharsets.UTF_8));
// }
/**
* 发送byte数组
* @param bytes
* @return
*/
public ModbusDto sendByte(byte[] bytes)
{
synchronized (lock)
{
if(open())
{
serialPort.writeBytes(bytes,bytes.length);
try {
ModbusDto reStr = dataQueue.poll(15, TimeUnit.SECONDS);
return reStr;
} catch (InterruptedException e) {
logger.error("等待串口返回数据异常!" + e);
}
}else{
logger.error("串口未打开!" );
return null;
}
}
return null;
}
private static byte[] readFromPort(SerialPort serialPort) throws Exception {
InputStream in = null;
byte[] bytes = null;
try {
if (serialPort != null) {
in = serialPort.getInputStream();
} else {
return null;
}
int bufflenth = in.available(); // 获取buffer里的数据长度
while (bufflenth > 0) {
bytes = new byte[bufflenth]; // 初始化byte数组为buffer中数据的长度
in.read(bytes);
bufflenth = in.available();
}
} catch (Exception e) {
throw e;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
throw e;
}
}
return bytes;
}
}
... ... @@ -146,6 +146,7 @@ public class CameraRtspHandle implements CameraHandle {
}
String rtspUrl = "rtsp://admin:"+OperatingData.sysConfig.getPassword()+"@"+ip+":554/h264/ch1/main/av_stream";
// FFmpegLogCallback.set();
grabber = new FFmpegFrameGrabber(rtspUrl);
// grabber.setOption("framerate", "30"); // 设置帧率为30帧/秒
// grabber.setOption("skip_frame", "nokey"); // 只抓取关键帧
... ... @@ -155,7 +156,9 @@ public class CameraRtspHandle implements CameraHandle {
// grabber.setOption("buffer_size", "4096"); // 设置缓冲区大小为1024字节
grabber.setVideoOption("rtsp_transport", "tcp");
grabber.setOption("stimeout", "2000000");
avutil.av_log_set_level(avutil.AV_LOG_ERROR);
// avutil.av_log_set_level(avutil.AV_LOG_ERROR);
grabber.setAudioChannels(0);
grabber.start();
while (!grabber.hasAudio() || !grabber.hasVideo())
{
... ...
... ... @@ -49,7 +49,7 @@ public class AgreementHandler extends MessageToMessageDecoder<String> {
@Override
protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
try {
logger.info("读取到数据:{}",msg);
logger.info("收到服务器数据:{}",msg);
if(StringUtils.isNotBlank(msg) && checkAgreement(msg))
{
CmdDto cmdDto = new CmdDto(msg);
... ...
... ... @@ -45,7 +45,9 @@ public class CfgdataService {
try {
CfgdataRequest cfgdataRequest = GsonConstructor.get().fromJson(data.toString(), CfgdataRequest.class);
Condata condata = cfgdataRequest.getCondata();
if(OperatingData.feederConfig.getCondata().getRunmode()==1)
if (null != condata)
{
if(OperatingData.feederConfig.getCondata().getRunmode()==1 && condata.getRunmode()==0)
{
String commd = FeederCommdUtil.controlData( FeederCommd06ResponseType.runmode,0);
logger.info("自动模式切换成手动模式");
... ... @@ -57,7 +59,6 @@ public class CfgdataService {
OperatingData.setClassObjecValue(feederConfig, (fieldname, fieldObject) -> {
try {
String commd = FeederCommdUtil.controlData( FeederCommd06ResponseType.valueOf(fieldname),(Integer) fieldObject);
logger.info("远程发送指令{}",commd);
InitService.serialPortService.sendHexData(commd); //通知串口
}catch (Exception e)
{
... ... @@ -66,6 +67,7 @@ public class CfgdataService {
throw new RuntimeException(e);
}
});
}
List<Integer[]> timerList = cfgdataRequest.getTimer();
if(null != timerList)
... ...
package com.zhonglai.luhui.smart.feeder.service.netty;
import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.config.ScheduledConfig;
import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
import com.zhonglai.luhui.smart.feeder.service.InitService;
import com.zhonglai.luhui.smart.feeder.service.feeder.AgreementHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class NettyClient {
private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
private ChannelHandlerContext ctx;
private EventLoopGroup groupThread;
private Channel channel;
public void run()
{
ScheduledConfig.scheduler.scheduleWithFixedDelay(() -> {
if(!isOpen())
{
close();
start();
}
},1,3,TimeUnit.SECONDS);
while (true)
{
if(null != ctx && ctx.channel().isActive() && ctx.channel().isOpen())
{
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private void start() {
// 创建EventLoopGroup,用于处理客户端的I/O操作
groupThread = new NioEventLoopGroup();
try {
// 创建Bootstrap实例,客户端启动对象
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(groupThread);
bootstrap.option(ChannelOption.SO_SNDBUF, 1024) // 设置发送缓冲大小
.option(ChannelOption.SO_RCVBUF, 1024) // 这是接收缓冲大小
.option(ChannelOption.SO_KEEPALIVE, true) ; // 保持连接
// 设置服务端Channel类型为NioSocketChannel作为通道实现
bootstrap.channel(NioSocketChannel.class);
// 设置客户端处理
bootstrap.handler(new Channellitializer(this));
// 绑定端口
ChannelFuture channelFuture = bootstrap.connect(OperatingData.sysConfig.getNettyConfig().getHost(), OperatingData.sysConfig.getNettyConfig().getPort()).sync();
channel = channelFuture.channel();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void close()
{
if (channel != null) {
channel.close();
}
if(null != groupThread)
{
try {
groupThread.shutdownGracefully();
} catch (Exception e) {
logger.info("服务端关闭资源失败【{}{}】",OperatingData.sysConfig.getNettyConfig().getHost(), OperatingData.sysConfig.getNettyConfig().getPort());
}
}
}
protected class Channellitializer extends ChannelInitializer
{
private NettyClient nettyClient;
public Channellitializer(NettyClient nettyClient)
{
this.nettyClient = nettyClient;
}
@Override
protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("StringEncoder", new StringEncoder(Charset.forName("gb2312")));
pipeline.addLast("StringDecoder", new StringDecoder(Charset.forName("gb2312")));
pipeline.addLast("AgreementHandler", new AgreementHandler());
}
}
public ChannelHandlerContext getCtx() {
if(null == ctx || !ctx.channel().isOpen())
{
close();
start();
}
return ctx;
}
public boolean isOpen()
{
if(null != ctx && ctx.channel().isActive() && ctx.channel().isOpen())
{
return true;
}
return false;
}
public void setCtx(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public static void main(String[] args) {
//配置参数
ConfigurationParameterService.initConfigurationParameter();
NettyClient nettyClient = new NettyClient();
nettyClient.start();
}
}
... ... @@ -4,6 +4,7 @@ import com.google.gson.JsonObject;
import com.ruoyi.common.utils.ByteUtil;
import com.zhonglai.luhui.smart.feeder.config.OperatingData;
import com.zhonglai.luhui.smart.feeder.dto.mqtt.CmdDto;
import com.zhonglai.luhui.smart.feeder.service.DateListenService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
... ... @@ -11,10 +12,13 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.mqtt.MqttMessage;
import org.apache.catalina.filters.ExpiresFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
public class MessageUtil {
private static final Logger logger = LoggerFactory.getLogger(MessageUtil.class);
public static void sendMandunMessage(ChannelHandlerContext ctx, InetSocketAddress recipient, String commd)
{
byte[] bs = ByteUtil.hexStringToByte(commd.trim().toUpperCase());
... ... @@ -34,6 +38,7 @@ public class MessageUtil {
* @param flush
*/
public static ChannelFuture sendMessage(ChannelHandlerContext ctx, Object msg, boolean flush) {
logger.info("给服务器发送数据:{}",msg);
return flush ? ctx.writeAndFlush(msg) : ctx.write(msg);
}
... ...