1.OPC UA 服务模拟软件,OPC UA 客户端软件,java 客户端源码,请指正
链接: https://pan.baidu.com/s/1_kvmUFkk8Y-HnxeavPEwag 密码: xe9m
2.OPC UA服务端
3.OPC UA 客户端软件,可用来验证OPC UA 服务是否正常
4.java 客户端代码
ExampleKeys.java 用来生成客户端凭证
UATcpParam.java 参数类
OpcTcpClientUtil.java OPC UA 客户端读写操作
TestOpcTcpClientUtil.java 测试客户端类
package com.tiger.uatcp;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.transport.security.Cert;
import org.opcfoundation.ua.transport.security.KeyPair;
import org.opcfoundation.ua.transport.security.PrivKey;
import org.opcfoundation.ua.utils.CertificateUtils;
public class ExampleKeys {
private static final String PRIVKEY_PASSWORD = "Opc.Ua";
public static KeyPair getCert(String applicationName,String hostName,String applicationUri) throws ServiceResultException{
File certFile = new File(applicationName + ".der");
File privKeyFile = new File(applicationName+ ".pem");
try {
Cert myCertificate = Cert.load( certFile );
PrivKey myPrivateKey = PrivKey.load( privKeyFile, PRIVKEY_PASSWORD );
return new KeyPair(myCertificate, myPrivateKey);
} catch (CertificateException e) {
throw new ServiceResultException( e );
} catch (IOException e) {
try {
KeyPair keys = CertificateUtils.createApplicationInstanceCertificate(applicationName, null, applicationUri, 3650, hostName);
keys.getCertificate().save(certFile);
keys.getPrivateKey().save(privKeyFile);
return keys;
} catch (Exception e1) {
throw new ServiceResultException( e1 );
}
} catch (NoSuchAlgorithmException e) {
throw new ServiceResultException( e );
} catch (InvalidKeyException e) {
throw new ServiceResultException( e );
} catch (InvalidKeySpecException e) {
throw new ServiceResultException( e );
} catch (NoSuchPaddingException e) {
throw new ServiceResultException( e );
} catch (InvalidAlgorithmParameterException e) {
throw new ServiceResultException( e );
} catch (IllegalBlockSizeException e) {
throw new ServiceResultException( e );
} catch (BadPaddingException e) {
throw new ServiceResultException( e );
} catch (InvalidParameterSpecException e) {
throw new ServiceResultException( e );
}
}
}
package com.tiger.uatcp;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
public class UATcpParam {
private String applicationName="myClient";
private String url;
private Integer authentication;//0:匿名;1:验证用户名、密码,2:certificate,3:IssuedToken
private String userName;
private String password;
private MessageSecurityMode securityMode;//None;Sign;Sign&Encrypt
private SecurityPolicy securityPolicie;//Basic128Rsa15;Basic256;Basic256Sha256
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getAuthentication() {
return authentication;
}
public void setAuthentication(Integer authentication) {
this.authentication = authentication;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MessageSecurityMode getSecurityMode() {
return securityMode;
}
public void setSecurityMode(MessageSecurityMode securityMode) {
this.securityMode = securityMode;
}
public SecurityPolicy getSecurityPolicie() {
return securityPolicie;
}
public void setSecurityPolicie(SecurityPolicy securityPolicie) {
this.securityPolicie = securityPolicie;
}
}
package com.tiger.uatcp;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.opcfoundation.ua.application.Application;
import org.opcfoundation.ua.application.Client;
import org.opcfoundation.ua.application.SessionChannel;
import org.opcfoundation.ua.builtintypes.DataValue;
import org.opcfoundation.ua.builtintypes.NodeId;
import org.opcfoundation.ua.builtintypes.StatusCode;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.Attributes;
import org.opcfoundation.ua.core.EndpointDescription;
import org.opcfoundation.ua.core.IdType;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.core.ReadResponse;
import org.opcfoundation.ua.core.ReadValueId;
import org.opcfoundation.ua.core.TimestampsToReturn;
import org.opcfoundation.ua.core.WriteResponse;
import org.opcfoundation.ua.core.WriteValue;
import org.opcfoundation.ua.transport.security.KeyPair;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
import org.opcfoundation.ua.utils.EndpointUtil;
public class OpcTcpClientUtil {
public static String[] read(UATcpParam param,NodeId[] nodeIds) throws ServiceResultException, UnknownHostException{
int len=nodeIds.length;
String[] resValue=new String[len];
SessionChannel mySession=getSession(param);
if(mySession==null){
return null;
}
try{
ReadValueId[] nodesToRead =new ReadValueId[len];
for (int i = 0; i < len; i++) {
ReadValueId r=new ReadValueId(nodeIds[i], Attributes.Value, null, null);
nodesToRead[i]=r;
}
ReadResponse res = mySession.Read(null, null, TimestampsToReturn.Neither,nodesToRead);
DataValue[] data=res.getResults();
for (int i = 0; i < len; i++) {
String val = data[i].getValue().getValue().toString();
resValue[i]=val;
}
return resValue;
}finally{
mySession.close();
mySession.closeAsync();
}
}
public static String[] write(UATcpParam param,WriteValue[] writeValues)throws ServiceResultException, UnknownHostException{
int len=writeValues.length;
String[] resValue=new String[len];
SessionChannel mySession=getSession(param);
if(mySession==null){
return null;
}
try{
WriteResponse res = mySession.Write(null, writeValues);
StatusCode[] data=res.getResults();
for (int i = 0; i < len; i++) {
resValue[i] = data[i].getValue().toString();
}
return resValue;
}finally{
mySession.close();
mySession.closeAsync();
}
}
public static SessionChannel getSession(UATcpParam param) throws ServiceResultException, UnknownHostException{
SessionChannel mySession =null;
Application myClientApplication = new Application();
Client myClient = new Client(myClientApplication);
if(param.getSecurityMode()!=null&&!param.getSecurityMode().equals(MessageSecurityMode.None)){
String hostName=InetAddress.getLocalHost().getHostName();
String applicationName=param.getApplicationName();
String applicationUri = "urn:"+hostName+":OPCUA:"+applicationName;
KeyPair myClientApplicationInstanceCertificate = ExampleKeys.getCert(applicationName,hostName,applicationUri);
myClientApplication.setApplicationUri(applicationUri);
myClientApplication.addApplicationInstanceCertificate(myClientApplicationInstanceCertificate);
EndpointDescription[] endpoints = myClient.discoverEndpoints(param.getUrl());
endpoints = EndpointUtil.selectByProtocol(endpoints, "opc.tcp");
endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, param.getSecurityMode());
if(param.getSecurityPolicie()!=null){
endpoints = EndpointUtil.selectBySecurityPolicy(endpoints, param.getSecurityPolicie());
}
endpoints = EndpointUtil.sortBySecurityLevel(endpoints);
if(endpoints.length==0){
return null;
}
EndpointDescription endpoint = endpoints[endpoints.length - 1];
mySession = myClient.createSessionChannel(endpoint);
}else{
mySession = myClient.createSessionChannel(param.getUrl());
}
if(param.getAuthentication()==0){//用户名密码验证֤
mySession.activate();
}else if(param.getAuthentication()==1){
mySession.activate(param.getUserName(), param.getPassword());
}else{
mySession.activate();
}
return mySession;
}
public static MessageSecurityMode getMessageSecurityMode(int type){
MessageSecurityMode mode=null;
switch(type){
case 1:
mode=MessageSecurityMode.None;
break;
case 2:
mode=MessageSecurityMode.Sign;
break;
case 3:
mode=MessageSecurityMode.SignAndEncrypt;
break;
default:
mode=MessageSecurityMode.None;
break;
}
return mode;
}
public static SecurityPolicy getSecurityPolicy(int type){
SecurityPolicy policy=null;
switch(type){
case 1:
policy=SecurityPolicy.BASIC128RSA15;
break;
case 2:
policy=SecurityPolicy.BASIC256;
break;
case 3:
policy=SecurityPolicy.BASIC256SHA256;
break;
default:
policy=SecurityPolicy.BASIC128RSA15;
break;
}
return policy;
}
public static int getNs(String nodeIdStr){
String[] addrArr=nodeIdStr.split(";");
String[] nsArr=addrArr[0].split("=");
return Integer.parseInt(nsArr[1]);
}
public static String getId(String nodeIdStr){
String[] addrArr=nodeIdStr.split(";");
String[] idArr=addrArr[1].split("=");
return idArr[1];
}
public static IdType getIdType(String nodeIdStr) {
String[] addrArr=nodeIdStr.split(";");
String[] addr=addrArr[1].split("=");
String type=addr[0];
if (type.equals("i"))
return IdType.Numeric;
if (type.equals("s"))
return IdType.String;
if (type.equals("g") )
return IdType.Guid;
if (type.equals("b") ) {
return IdType.Opaque;
}
return IdType.String;
}
}
package com.tiger.uatcp;
import java.net.UnknownHostException;
import org.opcfoundation.ua.builtintypes.DataValue;
import org.opcfoundation.ua.builtintypes.NodeId;
import org.opcfoundation.ua.builtintypes.Variant;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.Attributes;
import org.opcfoundation.ua.core.IdType;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.core.WriteValue;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
public class TestOpcTcpClientUtil {
private final static String url="opc.tcp://Atiger:53530/OPCUA/SimulationServer";
private static void testRead() throws ServiceResultException, UnknownHostException{
NodeId[] nodeIds=new NodeId[2];
nodeIds[0]=NodeId.get(IdType.String,5, "Random1");
nodeIds[1]=NodeId.get(IdType.String, 5, "Counter1");
UATcpParam param=new UATcpParam();
param.setUrl(url);
param.setAuthentication(0);
//param.setUserName("admin");
//param.setPassword("admin");
param.setSecurityMode(MessageSecurityMode.None);
//param.setSecurityPolicie(SecurityPolicy.BASIC128RSA15);
String[] result=OpcTcpClientUtil.read(param, nodeIds);
for (String rs : result) {
System.out.println(rs);
}
}
private static void testWrite() throws ServiceResultException, UnknownHostException{
UATcpParam param=new UATcpParam();
param.setUrl(url);
param.setAuthentication(0);
//param.setUserName("admin");
//param.setPassword("admin");
param.setSecurityMode(MessageSecurityMode.None);
//param.setSecurityPolicie(SecurityPolicy.BASIC128RSA15);
NodeId nodeId1=NodeId.get(IdType.String,5, "Random1");
NodeId nodeId2=NodeId.get(IdType.String, 5, "Counter1");
WriteValue v1=new WriteValue(nodeId1, Attributes.Value, null, new DataValue(new Variant(new Double(0.5))));
WriteValue v2=new WriteValue(nodeId2, Attributes.Value, null, new DataValue(new Variant(300)));
WriteValue[] nodesToWrite = {v1,v2};
String[] result=OpcTcpClientUtil.write(param, nodesToWrite);
for (String rs : result) {
System.out.println(rs);
}
}
private static void testReadNodeStr() throws UnknownHostException, ServiceResultException{
UATcpParam param=new UATcpParam();
param.setUrl(url);
param.setAuthentication(0);
//param.setUserName("admin");
//param.setPassword("admin");
param.setSecurityMode(MessageSecurityMode.None);
//param.setSecurityPolicie(SecurityPolicy.BASIC128RSA15);
String nodeIdStr1="ns=5;s=Random1";
String nodeIdStr2="ns=5;s=Counter1";
NodeId[] nodeIds=new NodeId[2];
nodeIds[0]=NodeId.get(OpcTcpClientUtil.getIdType(nodeIdStr1),OpcTcpClientUtil.getNs(nodeIdStr1), OpcTcpClientUtil.getId(nodeIdStr1));
nodeIds[1]=NodeId.get(OpcTcpClientUtil.getIdType(nodeIdStr2),OpcTcpClientUtil.getNs(nodeIdStr2), OpcTcpClientUtil.getId(nodeIdStr2));
String[] result=OpcTcpClientUtil.read(param, nodeIds);
for (String rs : result) {
System.out.println(rs);
}
}
public static void main(String[] args) {
try {
testWrite();
testRead();
testReadNodeStr();
} catch (ServiceResultException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.补充说明