use of org.apache.plc4x.java.api.exceptions.PlcConnectionException in project plc4x by apache.
the class Plc4xCommunication method setValue.
public void setValue(String tag, String value, String connectionString) {
PlcConnection connection = null;
try {
connection = driverManager.getConnection(connectionString);
if (connection.isConnected() == false) {
logger.debug("getConnection() returned a connection that isn't connected");
connection.connect();
}
} catch (PlcConnectionException e) {
logger.warn("Failed" + e);
}
if (!connection.getMetadata().canWrite()) {
logger.error("This connection doesn't support writing.");
try {
connection.close();
} catch (Exception e) {
logger.warn("Closing connection failed with error " + e);
}
return;
}
// Create a new read request:
// - Give the single item requested an alias name
final PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
// If an array value is passed instead of a single value then convert to a String array
if ((value.charAt(0) == '[') && (value.charAt(value.length() - 1) == ']')) {
String[] values = value.substring(1, value.length() - 1).split(",");
logger.info("Adding Tag " + Arrays.toString(values));
builder.addItem(tag, tag, values);
} else {
builder.addItem(tag, tag, value);
}
PlcWriteRequest writeRequest = builder.build();
try {
writeRequest.execute().get();
} catch (InterruptedException | ExecutionException e) {
logger.warn("Failed" + e);
}
try {
connection.close();
} catch (Exception e) {
logger.warn("Closing Connection Failed with error " + e);
}
return;
}
use of org.apache.plc4x.java.api.exceptions.PlcConnectionException in project plc4x by apache.
the class Plc4xNamespace method addConfiguredNodes.
private void addConfiguredNodes(UaFolderNode rootNode, DeviceConfiguration c) {
final List<Tag> tags = c.getTags();
final String connectionString = c.getConnectionString();
for (int i = 0; i < tags.size(); i++) {
logger.info("Adding Tag " + tags.get(i).getAlias() + " - " + tags.get(i).getAddress());
String name = tags.get(i).getAlias();
final String tag = tags.get(i).getAddress();
Class datatype = null;
NodeId typeId = Identifiers.String;
UaVariableNode node = null;
Variant variant = null;
try {
datatype = plc4xServer.getField(tag, connectionString).getDefaultJavaType();
final int length = plc4xServer.getField(tag, connectionString).getNumberOfElements();
typeId = Plc4xCommunication.getNodeId(plc4xServer.getField(tag, connectionString).getPlcDataType());
if (length > 1) {
node = new UaVariableNode.UaVariableNodeBuilder(getNodeContext()).setNodeId(newNodeId(name)).setAccessLevel(AccessLevel.READ_WRITE).setUserAccessLevel(AccessLevel.READ_WRITE).setBrowseName(newQualifiedName(name)).setDisplayName(LocalizedText.english(name)).setDataType(typeId).setTypeDefinition(Identifiers.BaseDataVariableType).setValueRank(ValueRank.OneDimension.getValue()).setArrayDimensions(new UInteger[] { uint(length) }).build();
Object array = Array.newInstance(datatype, length);
for (int j = 0; j < length; j++) {
Array.set(array, j, false);
}
variant = new Variant(array);
} else {
node = new UaVariableNode.UaVariableNodeBuilder(getNodeContext()).setNodeId(newNodeId(name)).setAccessLevel(AccessLevel.READ_WRITE).setUserAccessLevel(AccessLevel.READ_WRITE).setBrowseName(newQualifiedName(name)).setDisplayName(LocalizedText.english(name)).setDataType(typeId).setTypeDefinition(Identifiers.BaseDataVariableType).build();
variant = new Variant(0);
}
node.setValue(new DataValue(variant));
node.getFilterChain().addLast(AttributeFilters.getValue(ctx -> plc4xServer.getValue(ctx, tag, connectionString)));
node.getFilterChain().addLast(AttributeFilters.setValue((ctx, value) -> {
if (length > 1) {
plc4xServer.setValue(tag, Arrays.toString((Object[]) value.getValue().getValue()), connectionString);
} else {
plc4xServer.setValue(tag, value.getValue().getValue().toString(), connectionString);
}
}));
} catch (PlcConnectionException e) {
logger.info("Couldn't find data type");
System.exit(1);
}
getNodeManager().addNode(node);
rootNode.addOrganizes(node);
}
}
use of org.apache.plc4x.java.api.exceptions.PlcConnectionException in project plc4x by apache.
the class OpcuaPlcDriver method getConnection.
@Override
public PlcConnection getConnection(String connectionString) throws PlcConnectionException {
// Split up the connection string into it's individual segments.
Matcher matcher = URI_PATTERN.matcher(connectionString);
if (!matcher.matches()) {
throw new PlcConnectionException("Connection string doesn't match the format '{protocol-code}:({transport-code})?//{transport-host}(:{transport-port})(/{transport-endpoint})(?{parameter-string)?'");
}
final String protocolCode = matcher.group("protocolCode");
final String transportCode = (matcher.group("transportCode") != null) ? matcher.group("transportCode") : getDefaultTransport();
final String transportHost = matcher.group("transportHost");
final String transportPort = matcher.group("transportPort");
final String transportEndpoint = matcher.group("transportEndpoint");
final String paramString = matcher.group("paramString");
// Check if the protocol code matches this driver.
if (!protocolCode.equals(getProtocolCode())) {
// Actually this shouldn't happen as the DriverManager should have not used this driver in the first place.
throw new PlcConnectionException("This driver is not suited to handle this connection string");
}
// Create the configuration object.
OpcuaConfiguration configuration = (OpcuaConfiguration) new ConfigurationFactory().createConfiguration(getConfigurationType(), paramString);
if (configuration == null) {
throw new PlcConnectionException("Unsupported configuration");
}
configuration.setTransportCode(transportCode);
configuration.setHost(transportHost);
configuration.setPort(transportPort);
configuration.setTransportEndpoint(transportEndpoint);
configuration.setEndpoint("opc." + transportCode + "://" + transportHost + ":" + transportPort + "" + transportEndpoint);
// Try to find a transport in order to create a communication channel.
Transport transport = null;
ServiceLoader<Transport> transportLoader = ServiceLoader.load(Transport.class, Thread.currentThread().getContextClassLoader());
for (Transport curTransport : transportLoader) {
if (curTransport.getTransportCode().equals(transportCode)) {
transport = curTransport;
break;
}
}
if (transport == null) {
throw new PlcConnectionException("Unsupported transport " + transportCode);
}
// Inject the configuration into the transport.
configure(configuration, transport);
// Create an instance of the communication channel which the driver should use.
ChannelFactory channelFactory = transport.createChannelFactory(transportHost + ":" + transportPort);
if (channelFactory == null) {
throw new PlcConnectionException("Unable to get channel factory from url " + transportHost + ":" + transportPort);
}
configure(configuration, channelFactory);
// Give drivers the option to customize the channel.
initializePipeline(channelFactory);
// Make the "await setup complete" overridable via system property.
boolean awaitSetupComplete = awaitSetupComplete();
if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE) != null) {
awaitSetupComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE));
}
// Make the "await disconnect complete" overridable via system property.
boolean awaitDisconnectComplete = awaitDisconnectComplete();
if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE) != null) {
awaitDisconnectComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE));
}
if (configuration.getSecurityPolicy() != null && !(configuration.getSecurityPolicy().equals("None"))) {
try {
configuration.openKeyStore();
} catch (Exception e) {
throw new PlcConnectionException("Unable to open keystore, please confirm you have the correct permissions");
}
}
this.isEncrypted = configuration.isEncrypted();
// Make the "await disconnect complete" overridable via system property.
boolean awaitDiscoverComplete = awaitDiscoverComplete();
if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE) != null) {
awaitDiscoverComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE));
}
return new DefaultNettyPlcConnection(canRead(), canWrite(), canSubscribe(), getFieldHandler(), getValueHandler(), configuration, channelFactory, awaitSetupComplete, awaitDisconnectComplete, awaitDiscoverComplete, getStackConfigurer(), getOptimizer());
}
use of org.apache.plc4x.java.api.exceptions.PlcConnectionException in project plc4x by apache.
the class OpcuaConfiguration method openKeyStore.
public void openKeyStore() throws Exception {
this.isEncrypted = true;
File securityTempDir = new File(certDirectory, "security");
if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
throw new PlcConnectionException("Unable to create directory please confirm folder permissions on " + certDirectory);
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File serverKeyStore = securityTempDir.toPath().resolve(keyStoreFile).toFile();
File pkiDir = FileSystems.getDefault().getPath(certDirectory).resolve("pki").toFile();
if (!serverKeyStore.exists()) {
ckp = CertificateGenerator.generateCertificate();
LOGGER.info("Creating new KeyStore at {}", serverKeyStore);
keyStore.load(null, keyStorePassword.toCharArray());
keyStore.setKeyEntry("plc4x-certificate-alias", ckp.getKeyPair().getPrivate(), keyStorePassword.toCharArray(), new X509Certificate[] { ckp.getCertificate() });
keyStore.store(new FileOutputStream(serverKeyStore), keyStorePassword.toCharArray());
} else {
LOGGER.info("Loading KeyStore at {}", serverKeyStore);
keyStore.load(new FileInputStream(serverKeyStore), keyStorePassword.toCharArray());
String alias = keyStore.aliases().nextElement();
KeyPair kp = new KeyPair(keyStore.getCertificate(alias).getPublicKey(), (PrivateKey) keyStore.getKey(alias, keyStorePassword.toCharArray()));
ckp = new CertificateKeyPair(kp, (X509Certificate) keyStore.getCertificate(alias));
}
}
use of org.apache.plc4x.java.api.exceptions.PlcConnectionException in project plc4x by apache.
the class OpcuaPlcDriverTest method connectionWithDiscoveryParam.
@Test
public void connectionWithDiscoveryParam() {
connectionStringValidSet.forEach(connectionAddress -> {
discoveryParamValidSet.forEach(discoveryParam -> {
String connectionString = connectionAddress + paramSectionDivider + discoveryParam;
try {
PlcConnection opcuaConnection = new PlcDriverManager().getConnection(connectionString);
Condition<PlcConnection> is_connected = new Condition<>(PlcConnection::isConnected, "is connected");
assertThat(opcuaConnection).is(is_connected);
opcuaConnection.close();
assertThat(opcuaConnection).isNot(is_connected);
} catch (PlcConnectionException e) {
fail("Exception during connectionWithDiscoveryParam while connecting Test EXCEPTION: " + e.getMessage());
} catch (Exception e) {
fail("Exception during connectionWithDiscoveryParam while closing Test EXCEPTION: " + e.getMessage());
}
});
});
}
Aggregations