OPC UA Client read、write、history read(Java)

本文代码基于opc-ua-java-stack-1.02-source-code-and-sample-applications-337.2-stable
源码官网链接

  1. 参数信息类型
package OpcUa;

import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.transport.security.SecurityPolicy;

public class UAParam {
	
	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;
	}
}
  1. 证书类
package OpcUa;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
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;

/**
 * Keys for examples
 * Keystore.p12 contains 20 RSA keypairs with the following aliases
 * 
 * alias               dname
 * 
 * server_8192         CN=server 
 * server_4096         CN=server 
 * server_2048         CN=server
 * server_1024         CN=server
 * server_512          CN=server
 * 
 * client_8192         CN=client
 * client_4096         CN=client
 * client_2048         CN=client
 * client_1024         CN=client
 * client_512          CN=client
 * 
 * https_server_8192   CN=https_server
 * https_server_4096   CN=https_server
 * https_server_2048   CN=https_server
 * https_server_1024   CN=https_server
 * https_server_512    CN=https_server
 * 
 * https_client_8192   CN=https_client
 * https_client_4096   CN=https_client
 * https_client_2048   CN=https_client
 * https_client_1024   CN=https_client
 * https_client_512    CN=https_client
 * 
 * Keystore password is "password".
 * Private key passwords are "password".
 *
 */
public class ExampleKeys {
	
	private static final String PRIVKEY_PASSWORD = "Opc.Ua";
	
	/**
	 * Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
	 * @return the KeyPair composed of the certificate and private key
	 * @throws ServiceResultException
	 */
	public static KeyPair getCert1(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 );
		}
	}

	/**
	 * Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
	 * @return the KeyPair composed of the certificate and private key
	 * @throws ServiceResultException
	 */
	public static KeyPair getCert(String applicationName)
	throws ServiceResultException
	{
		File certFile = new File(applicationName + ".der");
		File privKeyFile =  new File(applicationName+ ".pem");
		try {
			Cert myServerCertificate = Cert.load( certFile );
			PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
			return new KeyPair(myServerCertificate, myServerPrivateKey); 
		} catch (CertificateException e) {
			throw new ServiceResultException( e );
		} catch (IOException e) {		
			try {
				String hostName = InetAddress.getLocalHost().getHostName();
				String applicationUri = "urn:"+hostName+":"+applicationName;
				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 (UnrecoverableKeyException e) {
			throw new ServiceResultException( e );
		} catch (NoSuchAlgorithmException e) {
			throw new ServiceResultException( e );
		} catch (KeyStoreException e) {
			throw new ServiceResultException( e );
		}
	}

	/**
	 * Load CA certificate and private key from SampleCA.der & .pfx - or create ones if they do not exist
	 * @return the KeyPair composed of the certificate and private key
	 * @throws ServiceResultException
	 */
	public static KeyPair getCACert()
	throws ServiceResultException
	{
		File certFile = new File("SampleCA.der");
		File privKeyFile =  new File("SampleCA.pem");
		try {
			Cert myServerCertificate = Cert.load( certFile );
			PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
			return new KeyPair(myServerCertificate, myServerPrivateKey); 
		} catch (CertificateException e) {
			throw new ServiceResultException( e );
		} catch (IOException e) {		
			try {
				KeyPair keys = CertificateUtils.createIssuerCertificate("SampleCA", 3650, null);
				keys.getCertificate().save(certFile);
				keys.getPrivateKey().save(privKeyFile, PRIVKEY_PASSWORD);
				return keys;
			} catch (Exception e1) {
				throw new ServiceResultException( e1 );
			}
		} catch (UnrecoverableKeyException e) {
			throw new ServiceResultException( e );
		} catch (NoSuchAlgorithmException e) {
			throw new ServiceResultException( e );
		} catch (KeyStoreException e) {
			throw new ServiceResultException( e );
		}
	}
	/**
	 * Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
	 * @param applicationName
	 * @param caKey 
	 * @return the KeyPair composed of the certificate and private key
	 * @throws ServiceResultException
	 */
	public static KeyPair getHttpsCert(String applicationName)
	throws ServiceResultException
	{
		File certFile = new File(applicationName + "_https.der");
		File privKeyFile =  new File(applicationName+ "_https.pem");
		try {
			Cert myServerCertificate = Cert.load( certFile );
			PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
			return new KeyPair(myServerCertificate, myServerPrivateKey); 
		} catch (CertificateException e) {
			throw new ServiceResultException( e );
		} catch (IOException e) {		
			try {
				KeyPair caCert = CertificateUtils.createIssuerCertificate(applicationName, 3650, null);;//getCACert();
				String hostName = InetAddress.getLocalHost().getHostName();
				String applicationUri = "urn:"+hostName+":"+applicationName;
				KeyPair keys = CertificateUtils.createHttpsCertificate(hostName, applicationUri, 3650, caCert);
				keys.getCertificate().save(certFile);
				keys.getPrivateKey().save(privKeyFile, PRIVKEY_PASSWORD);
				return keys;
			} catch (Exception e1) {
				throw new ServiceResultException( e1 );
			}
		} catch (UnrecoverableKeyException e) {
			throw new ServiceResultException( e );
		} catch (NoSuchAlgorithmException e) {
			throw new ServiceResultException( e );
		} catch (KeyStoreException e) {
			throw new ServiceResultException( e );
		}
	}
	/**
	 * Open keypair from keystore.p12 used in some of these examples.
	 * 
	 * Usable aliases are : "server", "client", "https_server", "https_client"
	 * Usable keysizes are : 8192, 4096, 2048, 1024
	 * 
	 * @param alias 
	 * @param keysize 
	 * @return
	 * @throws KeyStoreException 
	 * @throws IOException 
	 * @throws CertificateException 
	 * @throws NoSuchAlgorithmException 
	 * @throws UnrecoverableKeyException 
	 */
//	public static KeyPair getKeyPair(String alias, int keysize) throws ServiceResultException {
//		try {
//			Certificate cert = ks.getCertificate(alias+"_"+keysize);
//			Key key = ks.getKey(alias+"_"+keysize, "password".toCharArray());			
//			KeyPair pair = new KeyPair( new Cert( (X509Certificate) cert ), new PrivKey( (RSAPrivateKey) key ) );
//			return pair;
//		} catch (KeyStoreException e) {
//			throw new ServiceResultException( e );
//		} catch (UnrecoverableKeyException e) {
//			throw new ServiceResultException( e );
//		} catch (NoSuchAlgorithmException e) {
//			throw new ServiceResultException( e );
//		} catch (CertificateEncodingException e) {
//			throw new ServiceResultException( e );
//		}			
//	}	
//	
//	static KeyStore ks;
//	
//	static {
//		try {
//			ks = KeyStore.getInstance("pkcs12");
//			InputStream is = ExampleKeys.class.getResourceAsStream("keystore.p12");
//			try {
//				ks.load( is, "password".toCharArray() );
//			} catch (NoSuchAlgorithmException e) {
//				throw new RuntimeException(e);
//			} catch (CertificateException e) {
//				throw new RuntimeException(e);
//			} catch (IOException e) {
//				throw new RuntimeException(e);
//			} finally {
//				try {
//					is.close();
//				} catch (IOException e) {
//				}
//			}
//		} catch (KeyStoreException e) {
//			throw new RuntimeException(e);
//		}
//	}
	
	
}
  1. 工具类
package OpcUa;

import static org.opcfoundation.ua.utils.EndpointUtil.selectByProtocol;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;

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.DateTime;
import org.opcfoundation.ua.builtintypes.ExpandedNodeId;
import org.opcfoundation.ua.builtintypes.ExtensionObject;
import org.opcfoundation.ua.builtintypes.NodeId;
import org.opcfoundation.ua.builtintypes.QualifiedName;
import org.opcfoundation.ua.builtintypes.StatusCode;
import org.opcfoundation.ua.builtintypes.UnsignedInteger;
import org.opcfoundation.ua.builtintypes.Variant;
import org.opcfoundation.ua.common.ServiceFaultException;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.Attributes;
import org.opcfoundation.ua.core.BrowseDescription;
import org.opcfoundation.ua.core.BrowseDirection;
import org.opcfoundation.ua.core.BrowseResponse;
import org.opcfoundation.ua.core.BrowseResult;
import org.opcfoundation.ua.core.BrowseResultMask;
import org.opcfoundation.ua.core.EndpointDescription;
import org.opcfoundation.ua.core.HistoryData;
import org.opcfoundation.ua.core.HistoryReadResponse;
import org.opcfoundation.ua.core.HistoryReadResult;
import org.opcfoundation.ua.core.HistoryReadValueId;
import org.opcfoundation.ua.core.IdType;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.core.NodeClass;
import org.opcfoundation.ua.core.ReadRawModifiedDetails;
import org.opcfoundation.ua.core.ReadResponse;
import org.opcfoundation.ua.core.ReadValueId;
import org.opcfoundation.ua.core.ReferenceDescription;
import org.opcfoundation.ua.core.TimestampsToReturn;
import org.opcfoundation.ua.core.WriteResponse;
import org.opcfoundation.ua.core.WriteValue;
import org.opcfoundation.ua.encoding.EncoderContext;
import org.opcfoundation.ua.transport.security.KeyPair;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
import org.opcfoundation.ua.utils.EndpointUtil;
import org.opcfoundation.ua.utils.NumericRange;
import org.opcfoundation.ua.utils.StackUtils;

public class OpcUaUtil {
	public static long num = 0;
	private final static String url1 = "opc.tcp://xxxxx:53530/OPCUA/SimulationServer";
	private final static String url2 = "https://xxxxx:53443/OPCUA/SimulationServer";
	private static SessionChannel session = null;
	
	static{
		UAParam param = new UAParam();
		param.setUrl(url1);//tcp or https
		param.setAuthentication(1);
		param.setUserName("Cyril");
		param.setPassword("123123");
//		param.setSecurityMode(MessageSecurityMode.None);
		param.setSecurityMode(MessageSecurityMode.SignAndEncrypt);
		param.setSecurityPolicie(SecurityPolicy.BASIC256SHA256);
		try {
			session = getSession(param);
		} catch (UnknownHostException | ServiceResultException e) {
			e.printStackTrace();
			session = null;
		}
	}
	public static SessionChannel getSession() {
		return session;
	}
	public static SessionChannel getSession(UAParam param) throws ServiceResultException, UnknownHostException{
		String hostName = InetAddress.getLocalHost().getHostName();
		String applicationName = param.getApplicationName();
		String applicationUri = "urn:"+hostName+":OPCUA:"+applicationName;
		SessionChannel mySession =null;
		Application myClientApplication = new Application();
		Client myClient = new Client(myClientApplication);
		if(param.getSecurityMode()!=null&&!param.getSecurityMode().equals(MessageSecurityMode.None)){
			
			//证书要在Server端信任
			KeyPair myClientApplicationInstanceCertificate = ExampleKeys.getCert1(applicationName,hostName,applicationUri);
			myClientApplication.setApplicationUri(applicationUri);
			myClientApplication.addApplicationInstanceCertificate(myClientApplicationInstanceCertificate);
			KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("httpsClient");
			myClientApplication.getHttpsSettings().setKeyPair(myHttpsCertificate);
			
			// DISCOVER ENDPOINT /
			// Discover server's endpoints, and choose one
			EndpointDescription[] endpoints = myClient.discoverEndpoints(param.getUrl());
			// Filter out all but opc.tcp protocol endpoints
			if (param.getUrl().startsWith("opc.tcp")){
				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);
			}else{
				endpoints = selectByProtocol(endpoints, "https");
				EndpointDescription[] np = new EndpointDescription[1];
				np[0] = endpoints[0];
				endpoints = np;
			}
			//
			
			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;
	}
	
	
	/**
	 * History Read
	 * 
	 * @param mySession SessionChannel
	 * @param nodeIdStrs List<String> String => "ns=5;s=Random1"
	 * @param startTime Format => yyyy-MM-dd hh:mm:ss:SSS CST=>GMT
	 * @param endTime Format => yyyy-MM-dd hh:mm:ss:SSS CST=>GMT
	 */
	public static DataValue[] historyRead(SessionChannel mySession,List<String> nodeIdStrs,String startTime,String endTime) 
			throws ServiceFaultException, ServiceResultException, ParseException{
		if(mySession==null)
			mySession = session;
		if(nodeIdStrs==null || nodeIdStrs.size()<1)
			return null;
		List<NodeId> nodeIdList = new ArrayList<>();
		for (String nis : nodeIdStrs) {
			nodeIdList.add(NodeId.get(getIdType(nis),getNs(nis), getId(nis)));
		}
		
		ReadRawModifiedDetails rrmd = new ReadRawModifiedDetails();
		rrmd.setIsReadModified(false);
		
		SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
		Date s1 = ff.parse(startTime);
		Date s2 = ff.parse(endTime);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeZone(TimeZone.getTimeZone("GMT"));
		calendar1.setTime(s1);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTimeZone(TimeZone.getTimeZone("GMT"));
		calendar2.setTime(s2);
		
		rrmd.setStartTime(new DateTime(calendar1.get(Calendar.YEAR),calendar1.get(Calendar.MONTH),calendar1.get(Calendar.DAY_OF_MONTH)
				,calendar1.get(Calendar.HOUR),calendar1.get(Calendar.MINUTE),calendar1.get(Calendar.SECOND),calendar1.get(Calendar.MILLISECOND)));
		rrmd.setEndTime(new DateTime(calendar2.get(Calendar.YEAR),calendar2.get(Calendar.MONTH),calendar2.get(Calendar.DAY_OF_MONTH)
				,calendar2.get(Calendar.HOUR),calendar2.get(Calendar.MINUTE),calendar2.get(Calendar.SECOND),calendar2.get(Calendar.MILLISECOND)));
		
		rrmd.setNumValuesPerNode(UnsignedInteger.getFromBits(1000));
		rrmd.setReturnBounds(true);
		ExtensionObject eo = ExtensionObject.encode(rrmd, QualifiedName.DEFAULT_BINARY_ENCODING, StackUtils.getDefaultSerializer(), 
				EncoderContext.getDefaultInstance());
		
		HistoryReadValueId[] NodesToRead = new HistoryReadValueId[nodeIdStrs.size()];
		for (int i = 0; i < NodesToRead.length; i++) {
			HistoryReadValueId hrvi = new HistoryReadValueId();
			hrvi.setNodeId(nodeIdList.get(i));
			NumericRange parsedIndexRange = new NumericRange(-1);
			hrvi.setParsedIndexRange(parsedIndexRange);
			NodesToRead[i] = hrvi;
		}
		
		HistoryReadResponse resp = mySession.HistoryRead(null, eo, TimestampsToReturn.Source, false, NodesToRead);
		HistoryReadResult[] hrr = resp.getResults();
		for (HistoryReadResult historyReadResult : hrr) {
			HistoryReadResult tt = historyReadResult;
			ExtensionObject dc = tt.getHistoryData();
			HistoryData data = ((ExtensionObject) dc).decode(StackUtils.getDefaultSerializer(), EncoderContext.getDefaultInstance(), null);
			DataValue[] dataArr = data.getDataValues();
			return dataArr;
		}
		return null;
	}
	
	/**
	 * Write Nodes
	 * 
	 * @param mySession SessionChannel
	 * @param nodeIdStrs List<String> String => "ns=5;s=Random1"
	 * @param values datas for write
	 */
	public static boolean writeNodes(SessionChannel mySession,List<String> nodeIdStrs,List<Object> values){
		if(mySession==null)
			mySession = session;
		if(nodeIdStrs==null)
			return false;
		int len=nodeIdStrs.size();
		String[] resValue=new String[len];
		try{
			List<WriteValue> vList = new ArrayList<>();
			for (int i = 0; i < nodeIdStrs.size(); i++) {
				NodeId nid = NodeId.get(getIdType(nodeIdStrs.get(i)),getNs(nodeIdStrs.get(i)), getId(nodeIdStrs.get(i)));
				WriteValue v1 = new WriteValue(nid, Attributes.Value, null, new DataValue(new Variant(values.get(i))));
				vList.add(v1);
			}
			WriteValue[] writeValues = vList.toArray(new WriteValue[vList.size()]);
			WriteResponse res = mySession.Write(null, writeValues);
		    StatusCode[] data=res.getResults();
		    for (int i = 0; i < len; i++) {
		    	resValue[i] = data[i].getValue().toString();
			}
		    return true;
		} catch (ServiceResultException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * Read Nodes
	 * 
	 * @param mySession SessionChannel
	 * @param nodeIdStrs List<String> String => "ns=5;s=Random1"
	 */
	public static List<String> readNodes(SessionChannel mySession,List<String> nodeIdStrs){
		if(mySession==null)
			mySession = session;
		List<String> result = new ArrayList<String>();
		if(nodeIdStrs==null)
			return null;
		List<NodeId> nodeIdList = new ArrayList<>();
		for (String nis : nodeIdStrs) {
			nodeIdList.add(NodeId.get(getIdType(nis),getNs(nis), getId(nis)));
		}
		int len = nodeIdList.size();
		String[] resValue=new String[len];
		NodeId[] nodeIds = new NodeId[len];
		nodeIdList.toArray(nodeIds);
		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++) {
		    	Object v = data[i].getValue().getValue();
		    	String val = null;
		    	if(v!=null)
		    		val = v.toString();
		    	resValue[i] = val;
		    }
		    for (String v : resValue) {
		    	result.add(v);
			}
		} catch (ServiceResultException e) {
			e.printStackTrace();
		}
		return result;
	} 
	
	/**
	 * Browse Single Node
	 * 
	 * @param mySession SessionChannel
	 * @param nodeIdStr String => "ns=5;s=Random1"
	 */
	public static List<ReferenceDescription[]> browseNode(SessionChannel mySession,String nodeIdStr) throws ServiceFaultException, ServiceResultException{
		List<ReferenceDescription[]> list = new ArrayList<>();
		if(mySession==null)
			mySession = session;
		NodeId nodeId = NodeId.get(getIdType(nodeIdStr),getNs(nodeIdStr), getId(nodeIdStr));
		BrowseDescription browse = new BrowseDescription();
		browse.setNodeId(nodeId);
		browse.setBrowseDirection(BrowseDirection.Forward);
		browse.setIncludeSubtypes(true);
		browse.setNodeClassMask(NodeClass.Object/*,NodeClass.ObjectType*/,NodeClass.Variable);//可选
		browse.setResultMask(BrowseResultMask.All);//可选
		BrowseResponse res3 = mySession.Browse(null, null, null, browse);
		BrowseResult[] browseResults = res3.getResults();
		for (BrowseResult re : browseResults) {
			ReferenceDescription[] reference = re.getReferences();
			list.add(reference);
		}
		return list;
	}

	/**
	 * Browse All Sub Nodes From A Given Node
	 * 
	 * @param mySession SessionChannel
	 * @param nodeIdStr "ns=5;s=Random1"
	 */
	public static void deepBrowseNode(SessionChannel mySession,String nodeIdStr,Map<Integer,Object> map,Integer n) throws ServiceFaultException, ServiceResultException{
		if(nodeIdStr == null)
			return;
		String space = "";
		for (int i = 0; i < n; i++) {
			space += "";
		}
		String s1 = String.format("%-4d", OpcUaUtil.num);
		String s2 = String.format("%-3d", n);
		System.out.println(s1+" "+s2+" : "+space+nodeIdStr);
		OpcUaUtil.num++;
		List<ReferenceDescription[]> list = OpcUaUtil.browseNode(mySession, nodeIdStr);
		for (ReferenceDescription[] referenceDescriptions : list) {
			if(referenceDescriptions==null)
				System.out.println("null");
			else{
				for (ReferenceDescription rd : referenceDescriptions) {
					ExpandedNodeId nid = rd.getNodeId();
					nodeIdStr = "ns="+nid.getNamespaceIndex()+";"+getIdType2(nid.getIdType())+"="+nid.getValue();
					deepBrowseNode(mySession,nodeIdStr,map,n+1);
				}
			}
		}
		return;
	}
	
	public static Object getId(String nodeIdStr){
		String[] addrArr=nodeIdStr.split(";");
		String[] idArr=addrArr[1].split("=");
		String type=idArr[0];
		if (type.equals("i"))
			return UnsignedInteger.getFromBits(Integer.valueOf(idArr[1]));
//		if (type.equals("s")) 
//			return idArr.String;
		if (type.equals("g") ) 
			return UUID.fromString(idArr[1]);
//		if (type.equals("b")  ) {
//			return UUID.fromString(idArr[1]);
//		}
		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;
	}
	
	public static String getIdType2(IdType type) {
		if (type.equals(IdType.Numeric))
			return "i";
		if (type.equals(IdType.String)) 
			return "s";
		if (type.equals(IdType.Guid) ) 
			return "g";
		if (type.equals(IdType.Opaque)  ) {
			return "b";
		}
		return "s";
	}
	
	public static int getNs(String nodeIdStr){
		String[] addrArr=nodeIdStr.split(";");
		String[] nsArr=addrArr[0].split("=");
		return Integer.parseInt(nsArr[1]);
	}
	
}
  1. 测试类
package OpcUa;

import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.opcfoundation.ua.application.SessionChannel;
import org.opcfoundation.ua.builtintypes.DataValue;
import org.opcfoundation.ua.builtintypes.DateTime;
import org.opcfoundation.ua.builtintypes.ExpandedNodeId;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.ReferenceDescription;

import utils.OpcUaUtil;

public class OpcTest {
	public static void main(String[] args) throws UnknownHostException, ServiceResultException, ParseException {
		SessionChannel session = OpcUaUtil.getSession();
		
		//read
		List<String> list = Arrays.asList("ns=5;s=Counter1");
		List<String> re = OpcUaUtil.readNodes(session, list);
		for (String string : re) {
			System.out.println(string);
		}
		
		//browse
/*		String nodeIdStr = "ns=0;i=3048";
		List<ReferenceDescription[]> list = OpcUaUtil.browseNode(session, nodeIdStr);
		for (ReferenceDescription[] referenceDescriptions : list) {
			if(referenceDescriptions==null)
				System.out.println("null");
			else{
				for (ReferenceDescription rd : referenceDescriptions) {
					ExpandedNodeId nid = rd.getNodeId();
					System.out.println("ns="+nid.getNamespaceIndex()+";"+OpcUaUtil.getIdType2(nid.getIdType())+"="+nid.getValue());
				}
			}
		}*/
		
/*		//deep browse
		String nodeIdStr = "ns=0;i=2311";
		OpcUaUtil.deepBrowseNode(session,nodeIdStr,null,0);*/

		//historyRead
/*		SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		bjSdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));  // 设置北京时区
		
		List<String> list = Arrays.asList("ns=5;s=Random1");
		DataValue[] re = OpcUaUtil.historyRead(session, list, "2018-12-07 08:45:00:000", "2018-12-07 08:45:10:000");
		for (DataValue dataValue : re) {
			DateTime dt = dataValue.getSourceTimestamp();
			Calendar cc = dt.getUtcCalendar();
			System.out.println(String.format("%-25s", dataValue.getValue())+" "+bjSdf.format(cc.getTime()));
		}*/
		

		
		//write
/*		List<String> sList = Arrays.asList("ns=3;s=Duration");
		List<Object> vList = Arrays.asList(new Double(33));
		boolean re = OpcUaUtil.writeNodes(null, sList, vList);
		System.out.println(re);*/
		
		session.close();
		session.closeAsync();
	}
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值