Search in sources :

Example 1 with ModbusConnectionException

use of org.openhab.core.io.transport.modbus.exception.ModbusConnectionException in project openhab-addons by openhab.

the class ModbusDataThingHandler method onError.

private synchronized void onError(ModbusWriteRequestBlueprint request, Exception error) {
    if (hasConfigurationError()) {
        return;
    } else if (!isWriteEnabled) {
        return;
    }
    if (error instanceof ModbusConnectionException) {
        logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(), error.getClass().getSimpleName(), error.toString());
    } else if (error instanceof ModbusTransportException) {
        logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(), error.getClass().getSimpleName(), error.toString());
    } else {
        logger.error("Thing {} '{}' had {} error on write: {} (message: {}). Stack trace follows since this is unexpected error.", getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(), error.getMessage(), error);
    }
    Map<ChannelUID, State> states = new HashMap<>();
    ChannelUID lastWriteErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_ERROR);
    if (isLinked(lastWriteErrorUID)) {
        states.put(lastWriteErrorUID, new DateTimeType());
    }
    synchronized (this) {
        // Update channels
        states.forEach((uid, state) -> {
            tryUpdateState(uid, state);
        });
        updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Error (%s) with write. Request: %s. Description: %s. Message: %s", error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
    }
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) ModbusTransportException(org.openhab.core.io.transport.modbus.exception.ModbusTransportException) HashMap(java.util.HashMap) ChannelUID(org.openhab.core.thing.ChannelUID) State(org.openhab.core.types.State) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException)

Example 2 with ModbusConnectionException

use of org.openhab.core.io.transport.modbus.exception.ModbusConnectionException in project openhab-core by openhab.

the class SmokeTest method testSlaveConnectionError.

/**
 * Test handling of connection error responses.
 *
 * @throws Exception
 */
@Test
public void testSlaveConnectionError() throws Exception {
    // In the test we have non-responding slave (see http://stackoverflow.com/a/904609), and we use short connection
    // timeout
    ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("10.255.255.1", 9999, false);
    EndpointPoolConfiguration configuration = new EndpointPoolConfiguration();
    configuration.setConnectTimeoutMillis(100);
    AtomicInteger okCount = new AtomicInteger();
    AtomicInteger errorCount = new AtomicInteger();
    CountDownLatch callbackCalled = new CountDownLatch(1);
    AtomicReference<Exception> lastError = new AtomicReference<>();
    try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, configuration)) {
        comms.submitOneTimePoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID, ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 0, 5, 1), result -> {
            assert result.getRegisters().isPresent();
            okCount.incrementAndGet();
            callbackCalled.countDown();
        }, failure -> {
            errorCount.incrementAndGet();
            lastError.set(failure.getCause());
            callbackCalled.countDown();
        });
        assertTrue(callbackCalled.await(60, TimeUnit.SECONDS));
        assertThat(okCount.get(), is(equalTo(0)));
        assertThat(errorCount.get(), is(equalTo(1)));
        assertTrue(lastError.get() instanceof ModbusConnectionException, lastError.toString());
    }
}
Also used : ModbusSlaveEndpoint(org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint) EndpointPoolConfiguration(org.openhab.core.io.transport.modbus.endpoint.EndpointPoolConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) ModbusTCPSlaveEndpoint(org.openhab.core.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint) ModbusCommunicationInterface(org.openhab.core.io.transport.modbus.ModbusCommunicationInterface) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException) IOException(java.io.IOException) ModbusSlaveErrorResponseException(org.openhab.core.io.transport.modbus.exception.ModbusSlaveErrorResponseException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ModbusSlaveIOException(org.openhab.core.io.transport.modbus.exception.ModbusSlaveIOException) Test(org.junit.jupiter.api.Test)

Example 3 with ModbusConnectionException

use of org.openhab.core.io.transport.modbus.exception.ModbusConnectionException in project openhab-core by openhab.

the class ModbusManagerImpl method getConnection.

/**
 * Establishes connection to the endpoint specified by the task
 *
 * In case connection cannot be established, callback is called with {@link ModbusConnectionException}
 *
 * @param operationId id appened to log messages for identifying the operation
 * @param oneOffTask whether this is one-off, or execution of previously scheduled poll
 * @param task task representing the read or write operation
 * @return {@link ModbusSlaveConnection} to the endpoint as specified by the task, or empty {@link Optional} when
 *         connection cannot be established
 * @throws PollTaskUnregistered
 */
private <R, C extends ModbusResultCallback, F extends ModbusFailureCallback<R>, T extends TaskWithEndpoint<R, C, F>> Optional<ModbusSlaveConnection> getConnection(AggregateStopWatch timer, boolean oneOffTask, @NonNull T task) throws PollTaskUnregistered {
    KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool = this.connectionPool;
    if (connectionPool == null) {
        return Optional.empty();
    }
    String operationId = timer.operationId;
    logger.trace("Executing task {} (oneOff={})! Waiting for connection. Idle connections for this endpoint: {}, and active {} [operation ID {}]", task, oneOffTask, connectionPool.getNumIdle(task.getEndpoint()), connectionPool.getNumActive(task.getEndpoint()), operationId);
    long connectionBorrowStart = System.currentTimeMillis();
    ModbusFailureCallback<R> failureCallback = task.getFailureCallback();
    ModbusSlaveEndpoint endpoint = task.getEndpoint();
    R request = task.getRequest();
    Optional<ModbusSlaveConnection> connection = timer.connection.timeSupplier(() -> borrowConnection(endpoint));
    logger.trace("Executing task {} (oneOff={})! Connection received in {} ms [operation ID {}]", task, oneOffTask, System.currentTimeMillis() - connectionBorrowStart, operationId);
    if (scheduledThreadPoolExecutor == null) {
        // manager deactivated
        timer.connection.timeRunnable(() -> invalidate(endpoint, connection));
        return Optional.empty();
    }
    if (!connection.isPresent()) {
        logger.warn("Could not connect to endpoint {} -- aborting request {} [operation ID {}]", endpoint, request, operationId);
        timer.callback.timeRunnable(() -> invokeCallbackWithError(request, failureCallback, new ModbusConnectionException(endpoint)));
    }
    return connection;
}
Also used : ModbusSlaveEndpoint(org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException) ModbusSlaveConnection(net.wimpi.modbus.net.ModbusSlaveConnection)

Example 4 with ModbusConnectionException

use of org.openhab.core.io.transport.modbus.exception.ModbusConnectionException in project openhab-addons by openhab.

the class ModbusDataThingHandler method onError.

private synchronized void onError(ModbusReadRequestBlueprint request, Exception error) {
    if (hasConfigurationError()) {
        return;
    } else if (!isReadEnabled) {
        return;
    }
    if (error instanceof ModbusConnectionException) {
        logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(), error.getClass().getSimpleName(), error.toString());
    } else if (error instanceof ModbusTransportException) {
        logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(), error.getClass().getSimpleName(), error.toString());
    } else {
        logger.error("Thing {} '{}' had {} error on read: {} (message: {}). Stack trace follows since this is unexpected error.", getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(), error.getMessage(), error);
    }
    Map<ChannelUID, State> states = new HashMap<>();
    ChannelUID lastReadErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_ERROR);
    if (isLinked(lastReadErrorUID)) {
        states.put(lastReadErrorUID, new DateTimeType());
    }
    synchronized (this) {
        // Update channels
        states.forEach((uid, state) -> {
            tryUpdateState(uid, state);
        });
        updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Error (%s) with read. Request: %s. Description: %s. Message: %s", error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
    }
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) ModbusTransportException(org.openhab.core.io.transport.modbus.exception.ModbusTransportException) HashMap(java.util.HashMap) ChannelUID(org.openhab.core.thing.ChannelUID) State(org.openhab.core.types.State) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException)

Aggregations

ModbusConnectionException (org.openhab.core.io.transport.modbus.exception.ModbusConnectionException)4 HashMap (java.util.HashMap)2 ModbusSlaveEndpoint (org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint)2 ModbusTransportException (org.openhab.core.io.transport.modbus.exception.ModbusTransportException)2 DateTimeType (org.openhab.core.library.types.DateTimeType)2 ChannelUID (org.openhab.core.thing.ChannelUID)2 State (org.openhab.core.types.State)2 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 ModbusSlaveConnection (net.wimpi.modbus.net.ModbusSlaveConnection)1 Test (org.junit.jupiter.api.Test)1 ModbusCommunicationInterface (org.openhab.core.io.transport.modbus.ModbusCommunicationInterface)1 ModbusReadRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint)1 EndpointPoolConfiguration (org.openhab.core.io.transport.modbus.endpoint.EndpointPoolConfiguration)1 ModbusTCPSlaveEndpoint (org.openhab.core.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint)1 ModbusSlaveErrorResponseException (org.openhab.core.io.transport.modbus.exception.ModbusSlaveErrorResponseException)1 ModbusSlaveIOException (org.openhab.core.io.transport.modbus.exception.ModbusSlaveIOException)1