首先需要一些jar包
<dependency>
<groupId>jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jinterop</groupId>
<artifactId>j-interop</artifactId>
<version>3.0.0</version>
<exclusions>
<exclusion>
<artifactId>jcifs</artifactId>
<groupId>org.samba.jcifs</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.openscada.opc</groupId>
<artifactId>dcom</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.openscada.opc</groupId>
<artifactId>opc-lib</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.openscada.opc</groupId>
<artifactId>opc-xmlda</artifactId>
<version>1.4.0</version>
</dependency>
有的依赖以后,就可以开始写JAVA代码
public static void main(String[] args) {
try {
JISystem.setAutoRegisteration(true);
ConnectionInformation ci = new ConnectionInformation();
//OPC安装机器的IP
ci.setHost("172.27.9.227");
//CLSID 可以在注册表中找到对应的信息
ci.setClsid("7BC0CC8E-482C-47CA-ABDC-0FE7F9C6E729");
//此处是登陆WINDOWS的帐户和密码
ci.setUser("qy");
ci.setPassword("1234");
// create a new server
final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
try {
// connect to server
server.connect();
final AccessBase access = new SyncAccess(server, 1000);
//第一个参数就是写入的值对象,通过回调的changed方法 写入值
access.addItem("Medium laser.DVP40ES.D102", new DataCallback() {
@Override
public void changed(Item item, ItemState state) {
//写标识给 OPC Medium laser.DVP40ES.D102。
JIVariant value = JIVariant.makeVariant(new Integer(1));
try {
//通过wirte方法,把值写入OPC对象
item.write(value);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// start reading
access.bind();
// wait a little bit
// Thread.sleep(10 * 1000);
// stop reading
access.unbind();
} catch (final JIException e) {
System.out
.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (NotConnectedException e) {
e.printStackTrace();
} catch (DuplicateGroupException e) {
e.printStackTrace();
} catch (AddFailedException e) {
e.printStackTrace();
} catch (AlreadyConnectedException e1) {
e1.printStackTrace();
}
}