Witam,
oto moja udana próba połączenia i pobrania danych ze sterownika z wykorzystaniem czystej javy
program w eclipsie:
import java.net.*;
import java.io.*;
class poloczenie {
private String linia = "1";
public poloczenie()
// public (String lina)
{
try {
String sterownik = "192.168.1.101"; // adres ip sterownika
Socket s = new Socket(sterownik, 502);
try {
int unit = 01;//
int reg_no = 12228;// adres słowa
int num_regs = 1;// ilość słow
OutputStream os = s.getOutputStream();
FilterInputStream is = new BufferedInputStream(
s.getInputStream());
byte obuf[] = new byte[260];
byte ibuf[] = new byte[260];
int i;
// build request of form 0 0 0 0 0 6 ui 3 rr rr nn nn
for (i = 0; i < 5; i++)
obuf = 0;
obuf[5] = 6;
obuf[6] = (byte) unit;
obuf[7] = 03;
obuf[8] = (byte) (reg_no >> 8 ) ;
obuf[9] = (byte) (reg_no & 0xff ) ;
obuf[10] = (byte) (num_regs >> 8 ) ;
obuf[11] = (byte) (num_regs & 0xff ) ;
// send request
os.write(obuf, 0, 12);
// read response
i = is.read(ibuf, 0, 260);
if (i < 9) {
if (i == 0) {
System.out
.println("unexpected close of connection at remote end");
} else {
System.out.println("response was too short - " + i
+ " chars");
}
} else if (0 != (ibuf[7] & 0x80)) {
System.out.println("MODBUS exception response - type "
+ ibuf[8]);
} else if (i != (9 + 2 * num_regs)) {
System.out.println("incorrect response size is " + i +
" expected" + (9 + 2 * num_regs));
} else {
for (i = 0; i < num_regs; i++) {
int w = (ibuf[9 + i + i] << 8 ) + ibuf[10 + i + i];
linia = Integer.toString(w);
}
}
} finally {
s.close();
}
} catch (Exception e) {
}
}
public String getLinia() {
return linia;
}
}