【維普】軟件工程-軟件工程實(shí)驗(yàn)室室內(nèi)監(jiān)測系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)_第1頁
【維普】軟件工程-軟件工程實(shí)驗(yàn)室室內(nèi)監(jiān)測系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)_第2頁
【維普】軟件工程-軟件工程實(shí)驗(yàn)室室內(nèi)監(jiān)測系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)_第3頁
【維普】軟件工程-軟件工程實(shí)驗(yàn)室室內(nèi)監(jiān)測系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)_第4頁
【維普】軟件工程-軟件工程實(shí)驗(yàn)室室內(nèi)監(jiān)測系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)_第5頁
已閱讀5頁,還剩55頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

摘要附錄Modbus通訊核心代碼:SerialPortWrapperImpl.javapackage

org.jit.sose.modbus.tool;/**

*

*

Copyright

(c)

2009-2020

Freedomotic

Team

*

*

This

file

is

part

of

Freedomotic

*

*

This

Program

is

free

software;

you

can

redistribute

it

and/or

modify

it

under

*

the

terms

of

the

GNU

General

Public

License

as

published

by

the

Free

Software

*

Foundation;

either

version

2,

or

(at

your

option)

any

later

version.

*

*

This

Program

is

distributed

in

the

hope

that

it

will

be

useful,

but

WITHOUT

*

ANY

WARRANTY;

without

even

the

implied

warranty

of

MERCHANTABILITY

or

FITNESS

*

FOR

A

PARTICULAR

PURPOSE.

See

the

GNU

General

Public

License

for

more

*

details.

*

*

You

should

have

received

a

copy

of

the

GNU

General

Public

License

along

with

*

Freedomotic;

see

the

file

COPYING.

If

not,

see

*

</licenses/>.

*/import

com.serotonin.modbus4j.serial.SerialPortWrapper;import

jssc.SerialPort;import

org.slf4j.Logger;import

org.slf4j.LoggerFactory;import

java.io.InputStream;import

java.io.OutputStream;import

jssc.SerialPortException;/**

*

*/public

class

SerialPortWrapperImpl

implements

SerialPortWrapper

{

private

static

final

Logger

LOG

=

LoggerFactory.getLogger(SerialPortWrapperImpl.class);

private

SerialPort

port;

private

String

commPortId;

private

int

baudRate;

private

int

dataBits;

private

int

stopBits;

private

int

parity;

private

int

flowControlIn;

private

int

flowControlOut;

public

SerialPortWrapperImpl(String

commPortId,

int

baudRate,

int

dataBits,

int

stopBits,

int

parity,

int

flowControlIn,

int

flowControlOut)

{

mPortId

=

commPortId;

this.baudRate

=

baudRate;

this.dataBits

=

dataBits;

this.stopBits

=

stopBits;

this.parity

=

parity;

this.flowControlIn

=

flowControlIn;

this.flowControlOut

=

flowControlOut;

port

=

new

SerialPort(mPortId);

}

@Override

public

void

close()

throws

Exception

{

port.closePort();

//listeners.forEach(PortConnectionListener::closed);

LOG.debug("Serial

port

{}

closed",

port.getPortName());

}

@Override

public

void

open()

{

try

{

port.openPort();

port.setParams(this.getBaudRate(),

this.getDataBits(),

this.getStopBits(),

this.getParity());

port.setFlowControlMode(this.getFlowControlIn()

|

this.getFlowControlOut());

//listeners.forEach(PortConnectionListener::opened);

LOG.debug("Serial

port

{}

opened",

port.getPortName());

}

catch

(SerialPortException

ex)

{

LOG.error("Error

opening

port

:

{}

for

{}

",

port.getPortName(),

ex);

}

}

@Override

public

InputStream

getInputStream()

{

return

new

SerialInputStream(port);

}

@Override

public

OutputStream

getOutputStream()

{

return

new

SerialOutputStream(port);

}

@Override

public

int

getBaudRate()

{

return

baudRate;

//return

SerialPort.BAUDRATE_9600;

}

@Override

public

int

getFlowControlIn()

{

return

flowControlIn;

//return

SerialPort.FLOWCONTROL_NONE;

}

@Override

public

int

getFlowControlOut()

{

return

flowControlOut;

//return

SerialPort.FLOWCONTROL_NONE;

}

@Override

public

int

getDataBits()

{

return

dataBits;

//return

SerialPort.DATABITS_8;

}

@Override

public

int

getStopBits()

{

return

stopBits;

//return

SerialPort.STOPBITS_1;

}

@Override

public

int

getParity()

{

return

parity;

//return

SerialPort.PARITY_NONE;

}}SerialOutputStream.javapackageorg.jit.sose.modbus.tool;/****Copyright(c)2009-2020FreedomoticTeam**ThisfileispartofFreedomotic**ThisProgramisfreesoftware;youcanredistributeitand/ormodifyitunder*thetermsoftheGNUGeneralPublicLicenseaspublishedbytheFreeSoftware*Foundation;eitherversion2,or(atyouroption)anylaterversion.**ThisProgramisdistributedinthehopethatitwillbeuseful,butWITHOUT*ANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESS*FORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicenseformore*details.**YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwith*Freedomotic;seethefileCOPYING.Ifnot,see*</licenses/>.*/importjssc.SerialPort;importjssc.SerialPortException;importjava.io.IOException;importjava.io.OutputStream;/***Classthatwrapsa{@linkSerialPort}toprovide{@linkOutputStream}*functionality.*<br>*Itisinstantiatedbypassingtheconstructora{@linkSerialPort}instance.*Donotcreatemultiplestreamsforthesameserialportunlessyouimplement*yourownsynchronization.**@authorCharlesHache<chalz@>**Attribution:/therealchalz/java-simple-serial-connector**/publicclassSerialOutputStreamextendsOutputStream{SerialPortserialPort;/***InstantiatesaSerialOutputStreamforthegiven{@linkSerialPort}Donot*createmultiplestreamsforthesameserialportunlessyouimplement*yourownsynchronization.**@paramspTheserialporttostream.*/publicSerialOutputStream(SerialPortsp){serialPort=sp;}@Overridepublicvoidwrite(intb)throwsIOException{try{serialPort.writeInt(b);}catch(SerialPortExceptione){thrownewIOException(e);}}@Overridepublicvoidwrite(byte[]b)throwsIOException{write(b,0,b.length);}@Overridepublicvoidwrite(byte[]b,intoff,intlen)throwsIOException{byte[]buffer=newbyte[len];System.arraycopy(b,off,buffer,0,len);try{serialPort.writeBytes(buffer);}catch(SerialPortExceptione){thrownewIOException(e);}}}SerialInputStream.javapackageorg.jit.sose.modbus.tool;/**Tochangethistemplate,chooseTools|Templates*andopenthetemplateintheeditor.*/importjssc.SerialPort;importjava.io.IOException;importjava.io.InputStream;/***Classthatwrapsa{@linkSerialPort}toprovide{@linkInputStream}*functionality.Thisstreamalsoprovidessupportforperformingblocking*readswithtimeouts.*<br>*Itisinstantiatedbypassingtheconstructora{@linkSerialPort}instance.*Donotcreatemultiplestreamsforthesameserialportunlessyouimplement*yourownsynchronization.**@authorCharlesHache<chalz@>**Attribution:/therealchalz/java-simple-serial-connector**/publicclassSerialInputStreamextendsInputStream{privateSerialPortserialPort;privateintdefaultTimeout=0;/***InstantiatesaSerialInputStreamforthegiven{@linkSerialPort}Donot*createmultiplestreamsforthesameserialportunlessyouimplement*yourownsynchronization.**@paramspTheserialporttostream.*/publicSerialInputStream(SerialPortsp){serialPort=sp;}/***Setthedefaulttimeout(ms)ofthisSerialInputStream.Thisaffects*subsequentcallsto{@link#read()},{@link#blockingRead(int[])},and*{@link#blockingRead(int[],int,int)}Thedefaulttimeoutcanbe'unset'*bysettingitto0.**@paramtimeThetimeoutinmilliseconds.*/publicvoidsetTimeout(inttime){defaultTimeout=time;}/***Readsthenextbytefromtheport.Ifthetimeoutofthisstreamhasbeen*set,thenthismethodblocksuntildataisavailableoruntilthetimeout*hasbeenhit.Ifthetimeoutisnotsetorhasbeensetto0,thenthis*methodblocksindefinitely.*/@Overridepublicintread()throwsIOException{returnread(defaultTimeout);}/***Thesamecontractas{@link#read()},exceptoverridesthisstream's*defaulttimeoutwiththegiventimeoutinmilliseconds.**@paramtimeoutThetimeoutinmilliseconds.*@returnThereadbyte.*@throwsIOExceptionOnserialporterrorortimeout*/publicintread(inttimeout)throwsIOException{byte[]buf=newbyte[1];try{if(timeout>0){buf=serialPort.readBytes(1,timeout);}else{buf=serialPort.readBytes(1);}returnbuf[0];}catch(Exceptione){thrownewIOException(e);}}/***Non-blockingreadofuptobuf.lengthbytesfromthestream.Thiscall*behavesasread(buf,0,buf.length)would.**@parambufThebuffertofill.*@returnThenumberofbytesread,whichcanbe0.*@throwsIOExceptiononerror.*/@Overridepublicintread(byte[]buf)throwsIOException{returnread(buf,0,buf.length);}/***Non-blockingreadofuptolengthbytesfromthestream.Thismethod*returnswhatisimmediatelyavailableintheinputbuffer.**@parambufThebuffertofill.*@paramoffsetTheoffsetintothebuffertostartcopyingdata.*@paramlengthThemaximumnumberofbytestoread.*@returnTheactualnumberofbytesread,whichcanbe0.*@throwsIOExceptiononerror.*/@Overridepublicintread(byte[]buf,intoffset,intlength)throwsIOException{if(buf.length<offset+length){length=buf.length-offset;}intavailable=this.available();if(available>length){available=length;}try{byte[]readBuf=serialPort.readBytes(available);//System.arraycopy(readBuf,0,buf,offset,length);System.arraycopy(readBuf,0,buf,offset,readBuf.length);returnreadBuf.length;}catch(Exceptione){thrownewIOException(e);}}/***Blocksuntilbuf.lengthbytesareread,anerroroccurs,orthedefault*timeoutishit(ifspecified).ThisbehavesasblockingRead(buf,0,*buf.length)would.**@parambufThebuffertofillwithdata.*@returnThenumberofbytesread.*@throwsIOExceptionOnerrorortimeout.*/publicintblockingRead(byte[]buf)throwsIOException{returnblockingRead(buf,0,buf.length,defaultTimeout);}/***Thesamecontractas{@link#blockingRead(byte[])}exceptoverridesthis*stream'sdefaulttimeoutwiththegivenone.**@parambufThebuffertofill.*@paramtimeoutThetimeoutinmilliseconds.*@returnThenumberofbytesread.*@throwsIOExceptionOnerrorortimeout.*/publicintblockingRead(byte[]buf,inttimeout)throwsIOException{returnblockingRead(buf,0,buf.length,timeout);}/***Blocksuntillengthbytesareread,anerroroccurs,orthedefault*timeoutishit(ifspecified).Savesthedataintothegivenbufferat*thespecifiedoffset.Ifthestream'stimeoutisnotset,behavesas*{@link#read(byte[],int,int)}would.**@parambufThebuffertofill.*@paramoffsetTheoffsetinbuffertosavethedata.*@paramlengthThenumberofbytestoread.*@returnthenumberofbytesread.*@throwsIOExceptiononerrorortimeout.*/publicintblockingRead(byte[]buf,intoffset,intlength)throwsIOException{returnblockingRead(buf,offset,length,defaultTimeout);}/***Thesamecontractas{@link#blockingRead(byte[],int,int)}except*overridesthisstream'sdefaulttimeoutwiththegivenone.**@parambufThebuffertofill.*@paramoffsetOffsetinthebuffertostartsavingdata.*@paramlengthThenumberofbytestoread.*@paramtimeoutThetimeoutinmilliseconds.*@returnThenumberofbytesread.*@throwsIOExceptionOnerrorortimeout.*/publicintblockingRead(byte[]buf,intoffset,intlength,inttimeout)throwsIOException{if(buf.length<offset+length){thrownewIOException("Notenoughbufferspaceforserialdata");}if(timeout<1){returnread(buf,offset,length);}try{byte[]readBuf=serialPort.readBytes(length,timeout);System.arraycopy(readBuf,0,buf,offset,length);returnreadBuf.length;}catch(Exceptione){thrownewIOException(e);}}@Overridepublicintavailable()throwsIOException{intret;try{ret=serialPort.getInputBufferBytesCount();if(ret>=0){returnret;}thrownewIOException("Errorcheckingavailablebytesfromtheserialport.");}catch(Exceptione){thrownewIOException("Errorcheckingavailablebytesfromtheserialport.");}}}HardwareReadimpl.javapackageorg.jit.sose.modbus.impl;importcom.serotonin.modbus4j.ModbusMaster;importcom.serotonin.modbus4j.exception.ModbusTransportException;importcom.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;importcom.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;importcom.serotonin.modbus4j.msg.WriteRegistersRequest;importcom.serotonin.modbus4j.msg.WriteRegistersResponse;importorg.jit.sose.modbus.GetMaster;importorg.jit.sose.modbus.HardwareRead;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;publicclassHardwareReadimplimplementsHardwareRead{GetMastergetMaster;@OverridepublicReadHoldingRegistersResponseget_humdata(ModbusMastermaster,intSlaveId){try{//ModbusMastermaster=getMaster.getMaster("COM2",9600);//System.out.println("22222");ReadHoldingRegistersRequestrequest=newReadHoldingRegistersRequest(SlaveId,0x0003,1);ReadHoldingRegistersResponseresponse=(ReadHoldingRegistersResponse)master.send(request);if(response.isException()){System.out.println("Exceptionresponse:message="+response.getExceptionMessage());}else{System.out.println(Arrays.toString(response.getShortData()));short[]list=response.getShortData();for(inti=0;i<list.length;i++){System.out.print(list[i]+"");}}returnresponse;}catch(ModbusTransportExceptione){e.printStackTrace();returnnull;}}@Overridepublicbooleanget_infrared(ModbusMastermaster,intSlaveId){try{//ModbusMastermaster=getMaster.getMaster("COM2",9600);//System.out.println("22222");ReadHoldingRegistersRequestrequest=newReadHoldingRegistersRequest(SlaveId,0x0003,1);ReadHoldingRegistersResponseresponse=(ReadHoldingRegistersResponse)master.send(request);if(response.isException()){System.out.println("Exceptionresponse:message="+response.getExceptionMessage());}else{System.out.println(Arrays.toString(response.getShortData()));short[]list=response.getShortData();if(list[0]==1){returntrue;}}returnfalse;}catch(ModbusTransportExceptione){e.printStackTrace();returnfalse;}}@OverridepublicList<Integer>get_transmitte(ModbusMastermaster,intSlaveId){try{//ModbusMastermaster=getMaster.getMaster("COM2",9600);ReadHoldingRegistersRequestrequest=newReadHoldingRegistersRequest(SlaveId,0x0000,2);ReadHoldingRegistersResponseresponse=(ReadHoldingRegistersResponse)master.send(request);List<Integer>list1=null;if(response.isException()){System.out.println("Exceptionresponse:message="+response.getExceptionMessage());}else{System.out.println(Arrays.toString(response.getShortData()));short[]list=response.getShortData();//for(inti=0;i<list.length;i++){//System.out.print(list[i]+"");//}list1=newArrayList<Integer>();inttemp;if(list[1]>=65536){temp=-(list[1]-65536)/10;}else{temp=list[1]/10;}inthumi=list[0]/10;System.out.println(""+temp+""+humi);list1.add(temp);list1.add(humi);}returnlist1;}catch(ModbusTransportExceptione){e.printStackTrace();returnnull;}}@Overridepublicbooleanopen(ModbusMastermaster,intSlaveId){try{//ModbusMastermaster=getMaster.getMaster("COM2",9600);short[]b=newshort[1];shorta=bytes2Short2(int2byte(0x00ff));b[0]=a;WriteRegistersRequestrequest=newWriteRegistersRequest(SlaveId,0x0013,b);//System.out.println("request:"+request);//System.out.println("FunctionCode:"+request.getFunctionCode());//System.out.println("SlaveId:"+request.getSlaveId());WriteRegistersResponseresponse=(WriteRegistersResponse)master.send(request);if(response.isException()){System.out.println("Exceptionresponse:message="+response.getExceptionMessage());returnfalse;}else{System.out.println("Success");returntrue;}}catch(ModbusTransportExceptione){e.printStackTrace();}returnfalse;}@Overridepublicbooleanclose(ModbusMastermaster,intSlaveId){try{//ModbusMastermaster=getMaster.getMaster("COM2",9600);short[]b=newshort[1];shorta=bytes2Short2(int2byte(0x0000));b[0]=a;WriteRegistersRequestrequest=newWriteRegistersRequest(SlaveId,0x0013,b);//System.out.println("request:"+request);//System.out.println("FunctionCode:"+request.getFunctionCode());//System.out.println("SlaveId:"+request.getSlaveId());WriteRegistersResponseresponse=(WriteRegistersResponse)master.send(request);if(response.isException()){System.out.println("Exceptionresponse:

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論