赞
踩
首先根据需求,我这边使用的是springboot+netty的架构,使用了一个串口转网口的转换模块。为什么这么使用?部署的时候使用的是Linux的系统,在Linux下安装驱动比较麻烦,所以网口可以节省大量的服务器配置时间。为什么使用netty?不少使用过netty的人都知道,netty是一个异步非阻塞的框架,具体优势可以自己去查看一下,是一个功能非常强大的框架。转换模块使用的是有人的模块,淘宝上购买就行,也使用过其他厂家的模块,例如亿佰特,使用起来就没有人的好用,有人的模块还是相当做的成熟的。
提到485通信,大家就会想到modbus协议,Modbus 协议是应用于电子控制器上的一种通用语言。此处不过多讲解,这里我们使用的是modbus-rtu协议,这块后面会单独写一篇。
对这个架构有了一定的了解之后,我们就可以开始上代码了,首先我们要定义好服务端和客户端,如果我们这边的程序设置为服务端,模块就要设置为客户端,这个最后实现的效果是一样的,我本人更倾向于把程序这边设置为服务端。
监听程序会监听客户端连接
-
- import com.nari.sea.serialport.config.ServerChannelInitializer;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.*;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- import io.netty.handler.logging.LogLevel;
- import io.netty.handler.logging.LoggingHandler;
- import org.apache.log4j.Logger;
- import org.springframework.stereotype.Component;
- import java.net.InetSocketAddress;
-
- @Component
- public class NettyServer {
- private static final Logger logger = Logger.getLogger(NettyServer.class);
- public void start(InetSocketAddress address) {
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup(4);
- try {
- ServerBootstrap bootstrap = new ServerBootstrap()
- .group(bossGroup,workerGroup)
- .channel(NioServerSocketChannel.class)
- .localAddress(address)
- .handler(new LoggingHandler(LogLevel.INFO))
- .childHandler(new ServerChannelInitializer())
- .option(ChannelOption.SO_BACKLOG, 128)
- //开启长连接
- .childOption(ChannelOption.SO_KEEPALIVE, true);
- // 绑定端口,开始接收进来的连接
- ChannelFuture future = bootstrap.bind(address).sync();
- logger.info("Server start listen at " + address.getPort());
- future.channel().closeFuture().sync();
- } catch (Exception e) {
- e.printStackTrace();
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
- }
- }
这个里面的都是可自行根据需求配置的,netty默认的判断客户端离线是两个小时,通过下面的代码我们可以设置为几秒、几分钟,下面四个参数分别是读、写、全、时间类型。
channel.pipeline().addLast(new IdleStateHandler(1, 0, 0, TimeUnit.MINUTES));
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- import io.netty.handler.timeout.IdleStateHandler;
- import io.netty.util.CharsetUtil;
-
- import java.util.concurrent.TimeUnit;
-
- public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
- @Override
- protected void initChannel(SocketChannel channel) throws Exception {
- channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.ISO_8859_1));
- channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.ISO_8859_1));
- //设置n分钟判断离线
- channel.pipeline().addLast(new IdleStateHandler(1, 0, 0, TimeUnit.MINUTES));
- //粘包长度控制
- channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4));
- channel.pipeline().addLast(new ServerHandler());
- }
- }
-
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.channel.DefaultEventLoopGroup;
- import io.netty.handler.timeout.IdleState;
- import io.netty.handler.timeout.IdleStateEvent;
- import io.netty.util.CharsetUtil;
- import java.util.List;
-
-
- public class ServerHandler extends ChannelInboundHandlerAdapter {
- //超时连接
- private int lossConnectCount = 0;
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) {
- System.out.println("channelActive----->");
- }
-
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
- if (evt instanceof IdleStateEvent){
- IdleStateEvent event = (IdleStateEvent)evt;
- //只判断读
- if (event.state()== IdleState.READER_IDLE){
- lossConnectCount++;
- if (lossConnectCount>5){
- System.out.println("关闭不活跃通道!");
- ctx.channel().close();
- }
- System.out.println("已经"+lossConnectCount+"分钟未收到客户端的消息了!");
- }
- }else {
- super.userEventTriggered(ctx,evt);
- }
- }
-
- @Override
- public void handlerRemoved(ChannelHandlerContext ctx) throws Exception{
- //客户端退出连接
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- lossConnectCount = 0;
- System.out.println("server channelRead......");
- String m= (String) msg;
- //判断通信
- ByteBuf buf = Unpooled.copiedBuffer(m, CharsetUtil.ISO_8859_1);
- byte [] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- String returnData = bytes2HexString(bytes); //将byte数组转为16进制字符串
- System.out.println(ctx.channel().remoteAddress()+"----->Server :"+ returnData);
- if(returnData != null && !"".equals(returnData)){
- if(HexUtil.checkData(returnData)){
- //具体的逻辑代码
-
- }
- }
-
-
- //将客户端的信息直接返回写入ctx
- //刷新缓存区
- }
-
- private String bytes2HexString(byte[] b) {
- StringBuffer result = new StringBuffer();
- String hex;
- for (int i = 0; i < b.length; i++) {
- hex = Integer.toHexString(b[i] & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- result.append(hex.toUpperCase());
- }
- return result.toString();
- }
- private String hexString2String(String hex, String charset) {
- byte[] bs = new byte[hex.length()/2];
- for(int i=0; i<bs.length; i++) {
- bs[i] = (byte)(0xff&Integer.parseInt(hex.substring(i*2,i*2+2),16));
- }
- try{
- hex = new String(bs, charset);
- }catch(Exception e) {
- e.printStackTrace();
- }
- return hex;
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- cause.printStackTrace();
- ctx.close();
- }
- }
逻辑实现代码中,我们难免要引入一些service,这时候我们就需要在实现代码中这样操作了
- @Component
- public class SerialPortDealData {
- @Autowired
- private ModeManService modeManService;
-
- //声明对象
- private static SerialPortDealData serialPortDealData;
-
- // 初始化
- @PostConstruct
- public void init() {
- serialPortDealData = this;
- serialPortDealData.modeManService = this.modeManService;
- }
-
- //逻辑代码
- }
netty在springboot中的启动有很多,这里介绍其中一种
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.builder.SpringApplicationBuilder;
- import org.springframework.boot.web.servlet.ServletComponentScan;
- import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.annotation.EnableScheduling;
-
- import java.net.InetSocketAddress;
-
- @EnableScheduling
- @SpringBootApplication
- @ServletComponentScan//防止 @WebListener 无效
- @MapperScan(basePackages ={""})
- @ComponentScan(basePackages = {""})
- @EnableAsync//注意这里,这个注解启用了线程池
- public class SeaApplication extends SpringBootServletInitializer implements CommandLineRunner{
-
- @Value("${netty.port}")
- private int port;
-
- @Value("${netty.url}")
- private String url;
-
- @Autowired
- private NettyServer server;
-
-
- public static void main(String[] args) {
- SpringApplication.run(SeaApplication.class, args);
- }
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
- return builder.sources(SeaApplication.class);
- }
-
- @Override
- public void run(String... args) throws Exception {
- InetSocketAddress address = new InetSocketAddress(url,port);
- System.out.println("run .... . ... "+url);
- server.start(address);
- }
-
- }
applicaion.yml配置文件
- netty:
- port: 5001
- url: 127.0.0.1
到这里关于实现485通信的一种方法已经介绍完了,感谢你的阅读,有什么不足的地方请指导一下。最后说一下一些模拟工具,modbus poll-对应modbus slave,modbus scan,网络调试工具NetAssist.exe,串口调试工具等等
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。