use of org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException in project open-smart-grid-platform by OSGP.
the class BundleService method callExecutor.
private void callExecutor(final CommandExecutor<?, ?> executor, final ActionDto action, final DlmsConnectionManager conn, final DlmsDevice device, final MessageMetadata messageMetadata) {
final String executorName = executor.getClass().getSimpleName();
try {
log.info("Calling executor in bundle {} [deviceId={}]", executorName, device.getDeviceIdentification());
final ActionResponseDto response = executor.executeBundleAction(conn, device, action.getRequest(), messageMetadata);
action.setResponse(response);
} catch (final ConnectionException ce) {
log.warn("A connection exception occurred while executing {} [deviceId={}]", executorName, device.getDeviceIdentification(), ce);
throw ce;
} catch (final DeviceKeyProcessAlreadyRunningException e) {
// The request will NOT be sent back to Core to retry but put back on the queue
throw e;
} catch (final Exception e) {
log.error("Error while executing bundle action for {} with {} [deviceId={}]", action.getRequest().getClass().getName(), executorName, device.getDeviceIdentification(), e);
final String message = String.format("Error handling request with %s: %s", executorName, e.getMessage());
this.addFaultResponse(action, e, message, device);
}
}
use of org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException in project open-smart-grid-platform by OSGP.
the class BundleServiceTest method testConnectionException.
/**
* Tests the retry mechanism works in the adapter-protocol. In the first run a ConnectionException
* is thrown while executing the {@link FindEventsRequestDto}. In the second attempt (when the
* connection is restored again) the rest of the actions are executed.
*
* @throws ProtocolAdapterException is not thrown in this test
*/
@Test
public void testConnectionException() throws ProtocolAdapterException {
final List<ActionDto> actionDtoList = this.makeActions();
final BundleMessagesRequestDto dto = new BundleMessagesRequestDto(actionDtoList);
// Set the point where to throw the ConnectionException
this.getStub(FindEventsRequestDto.class).failWithRuntimeException(new ConnectionException("Connection Exception thrown!"));
try {
// Execute all the actions
this.callExecutors(dto, this.messageMetadata);
fail("A ConnectionException should be thrown");
} catch (final ConnectionException connectionException) {
// The execution is stopped. The number of responses is equal to the
// actions performed before the point the exception is thrown. See
// also the order of the ArrayList in method 'makeActions'.
assertThat(dto.getAllResponses().size()).isEqualTo(9);
}
// Reset the point where the exception was thrown.
this.getStub(FindEventsRequestDto.class).failWithRuntimeException(null);
try {
// Execute the remaining actions
this.callExecutors(dto, this.messageMetadata);
assertThat(actionDtoList.size()).isEqualTo(dto.getAllResponses().size());
} catch (final ConnectionException connectionException) {
fail("A ConnectionException should not have been thrown.");
}
}
use of org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException in project open-smart-grid-platform by OSGP.
the class DlmsConnectionHelper method createAndHandleConnectionForDevice.
private void createAndHandleConnectionForDevice(final DlmsDevice device, final DlmsMessageListener messageListener, final ConnectionProperties connectionProperties, final MessageMetadata messageMetadata, final Permit permit, final Consumer<DlmsConnectionManager> taskForConnectionManager) throws OsgpException {
if (connectionProperties.isPingDevice()) {
this.devicePingConfig.pinger().ping(device.getIpAddress());
}
if (connectionProperties.isInitializeInvocationCounter()) {
this.delay(connectionProperties.getWaitBeforeInitializingInvocationCounter());
this.invocationCounterManager.initializeInvocationCounter(messageMetadata, device);
}
try {
this.delay(connectionProperties.getWaitBeforeCreatingTheConnection());
this.connectionFactory.createAndHandleConnection(messageMetadata, device, messageListener, permit, taskForConnectionManager);
} catch (final ConnectionException e) {
if ((device.needsInvocationCounter() && this.indicatesInvocationCounterOutOfSync(e)) && !connectionProperties.isInitializeInvocationCounter()) {
LOGGER.warn("Invocation counter (stored value: {}) appears to be out of sync for {}, retry initializing the counter", device.getInvocationCounter(), device.getDeviceIdentification());
final ConnectionProperties newConnectionProperties = new ConnectionProperties(false, true, this.delayBetweenDlmsConnections, this.delayBetweenDlmsConnections);
/*
* The connection exception is likely caused by an already initialized invocation counter
* that does not have an appropriate value compared to the counter on the actual device.
* Retry creating the connection, do not ping anymore, as the device should have already
* been pinged if that was appropriate. Make sure the invocation counter is initialized,
* regardless of whether it has already been initialized before or not.
*/
this.createAndHandleConnectionForDevice(device, messageListener, newConnectionProperties, messageMetadata, permit, taskForConnectionManager);
return;
}
/*
* The connection exception is assumed not to be related to the invocation counter, or has
* occurred despite the attempt to initialize the invocation counter.
* Do not go into a loop trying to repeat setting up the connection possibly trying to
* initialize the invocation counter over and over again.
* Throw the connection exception and have other parts of the code decide whether or not a
* retry will be scheduled.
*/
throw e;
}
}
use of org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException in project open-smart-grid-platform by OSGP.
the class Hls5Connector method connect.
@Override
public DlmsConnection connect(final MessageMetadata messageMetadata, final DlmsDevice device, final DlmsMessageListener dlmsMessageListener) throws OsgpException {
// Make sure neither device or device.getIpAddress() is null.
this.checkDevice(device);
this.checkIpAddress(device);
try {
return this.createConnection(messageMetadata, device, dlmsMessageListener, this.secretManagementService::getKeys);
} catch (final UnknownHostException e) {
// Unknown IP, unrecoverable.
LOGGER.error("The IP address is not found: {}", device.getIpAddress(), e);
throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + device.getIpAddress());
} catch (final IOException e) {
// Queue key recovery process
if (this.secretManagementService.hasNewSecret(messageMetadata, device.getDeviceIdentification())) {
this.recoverKeyProcessInitiator.initiate(messageMetadata, device.getDeviceIdentification());
}
final String msg = String.format("Error creating connection for device %s with Ip address:%s Port:%d UseHdlc:%b UseSn:%b " + "Message:%s", device.getDeviceIdentification(), device.getIpAddress(), device.getPort(), device.isUseHdlc(), device.isUseSn(), e.getMessage());
LOGGER.error(msg);
throw new ConnectionException(msg, e);
} catch (final EncrypterException e) {
throw new FunctionalException(FunctionalExceptionType.INVALID_DLMS_KEY_FORMAT, ComponentType.PROTOCOL_DLMS, e);
}
}
use of org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException in project open-smart-grid-platform by OSGP.
the class SetEncryptionKeyExchangeOnGMeterCommandExecutor method execute.
@Override
public MethodResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final GMeterInfoDto gMeterInfo, final MessageMetadata messageMetadata) throws ProtocolAdapterException {
try {
LOGGER.debug("SetEncryptionKeyExchangeOnGMeterCommandExecutor.execute called");
final String mbusDeviceIdentification = gMeterInfo.getDeviceIdentification();
final int channel = gMeterInfo.getChannel();
final ObisCode obisCode = OBIS_HASHMAP.get(channel);
final byte[] gMeterEncryptionKey = this.secretManagementService.generate128BitsKeyAndStoreAsNewKey(messageMetadata, mbusDeviceIdentification, G_METER_ENCRYPTION);
MethodResult methodResultCode = this.transferKey(conn, mbusDeviceIdentification, channel, gMeterEncryptionKey, messageMetadata);
this.checkMethodResultCode(methodResultCode, "M-Bus Setup transfer_key", obisCode);
methodResultCode = this.setEncryptionKey(conn, channel, gMeterEncryptionKey);
this.checkMethodResultCode(methodResultCode, "M-Bus Setup set_encryption_key", obisCode);
this.secretManagementService.activateNewKey(messageMetadata, mbusDeviceIdentification, G_METER_ENCRYPTION);
return MethodResultCode.SUCCESS;
} catch (final IOException e) {
throw new ConnectionException(e);
} catch (final EncrypterException e) {
throw new ProtocolAdapterException("Unexpected exception during decryption of security keys, reason = " + e.getMessage(), e);
}
}
Aggregations