java实现modbus读写

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

packagecom.zsc;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;importcom.battery.bean.CommunityExceptionRecord;importcom.serotonin.modbus4j.ModbusFactory;importcom.serotonin.modbus4j.ModbusMaster;importcom.serotonin.modbus4j.exception.ModbusInitException;importcom.serotonin.modbus4j.exception.ModbusTransportException;importcom.serotonin.modbus4j.ip.IpParameters;importcom.serotonin.modbus4j.msg.ModbusRequest;importcom.serotonin.modbus4j.msg.ModbusResponse;importcom.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;importcom.serotonin.modbus4j.msg.WriteRegistersRequest;importcom.serotonin.modbus4j.msg.WriteRegistersResponse;importcom.serotonin.util.queue.ByteQueue;publicclassReadAWriteUtil{publicstaticvoidmodbusWTCP(Stringip,intport,intslaveId,intstart,short[]values){ModbusFactorymodbusFactory=newModbusFactory();//设备ModbusTCP的Ip与端口,如果不设定端口则默认为502IpParametersparams=newIpParameters();params.setHost(ip);if(502!=port){params.setPort(port);}//设置端口,默认502ModbusMastertcpMaster=null;//参数1:IP和端口信息参数2:保持连接激活tcpMaster=modbusFactory.createTcpMaster(params,true);try{tcpMaster.init();System.out.println(===============+1111111);}catch(ModbusInitExceptione){//System.out.println(11111111111111==+此处出现问题了啊!);//如果出现了通信异常信息,则保存到数据库中CommunityExceptionRecordcer=newCommunityExceptionRecord();cer.setDate(newDate());cer.setIp(ip);//cer.setRemark(bgName+出现连接异常);//batteryGroupRecordService.saveCommunityException(cer);}try{WriteRegistersRequestrequest=newWriteRegistersRequest(slaveId,start,values);WriteRegistersResponseresponse=(WriteRegistersResponse)tcpMaster.send(request);if(response.isException())System.out.println(Exceptionresponse:message=+response.getExceptionMessage());elseSystem.out.println(Success);}catch(ModbusTransportExceptione){e.printStackTrace();}}publicstaticByteQueuemodbusTCP(Stringip,intport,intstart,intreadLenth){ModbusFactorymodbusFactory=newModbusFactory();//设备ModbusTCP的Ip与端口,如果不设定端口则默认为502IpParametersparams=newIpParameters();params.setHost(ip);if(502!=port){params.setPort(port);}//设置端口,默认502ModbusMastertcpMaster=null;tcpMaster=modbusFactory.createTcpMaster(params,true);try{tcpMaster.init();System.out.println(===============+1111111);}catch(ModbusInitExceptione){returnnull;}ModbusRequestmodbusRequest=null;try{modbusRequest=newReadHoldingRegistersRequest(1,start,readLenth);//功能码03}catch(ModbusTransportExceptione){e.printStackTrace();}ModbusResponsemodbusResponse=null;try{modbusResponse=tcpMaster.send(modbusRequest);}catch(ModbusTransportExceptione){e.printStackTrace();}ByteQueuebyteQueue=newByteQueue(12);modbusResponse.write(byteQueue);System.out.println(功能码:+modbusRequest.getFunctionCode());System.out.println(从站地址:+modbusRequest.getSlaveId());System.out.println(收到的响应信息大小:+byteQueue.size());System.out.println(收到的响应信息值:+byteQueue);returnbyteQueue;}}

1 / 3
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功