Search in sources :

Example 6 with ModbusPollerThingHandler

use of org.openhab.binding.modbus.handler.ModbusPollerThingHandler in project openhab-addons by openhab.

the class ModbusDataThingHandler method initialize.

@Override
public synchronized void initialize() {
    // Long running initialization should be done asynchronously in background.
    try {
        logger.trace("initialize() of thing {} '{}' starting", thing.getUID(), thing.getLabel());
        ModbusDataConfiguration localConfig = config = getConfigAs(ModbusDataConfiguration.class);
        updateUnchangedValuesEveryMillis = localConfig.getUpdateUnchangedValuesEveryMillis();
        Bridge bridge = getBridge();
        if (bridge == null || !bridge.getStatus().equals(ThingStatus.ONLINE)) {
            logger.debug("Thing {} '{}' has no bridge or it is not online", getThing().getUID(), getThing().getLabel());
            updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, "No online bridge");
            return;
        }
        BridgeHandler bridgeHandler = bridge.getHandler();
        if (bridgeHandler == null) {
            logger.warn("Bridge {} '{}' has no handler.", bridge.getUID(), bridge.getLabel());
            String errmsg = String.format("Bridge %s '%s' configuration incomplete or with errors", bridge.getUID(), bridge.getLabel());
            throw new ModbusConfigurationException(errmsg);
        }
        if (bridgeHandler instanceof ModbusEndpointThingHandler) {
            // Write-only thing, parent is endpoint
            ModbusEndpointThingHandler endpointHandler = (ModbusEndpointThingHandler) bridgeHandler;
            slaveId = endpointHandler.getSlaveId();
            comms = endpointHandler.getCommunicationInterface();
            childOfEndpoint = true;
            functionCode = null;
            readRequest = null;
        } else {
            ModbusPollerThingHandler localPollerHandler = (ModbusPollerThingHandler) bridgeHandler;
            pollerHandler = localPollerHandler;
            ModbusReadRequestBlueprint localReadRequest = localPollerHandler.getRequest();
            if (localReadRequest == null) {
                logger.debug("Poller {} '{}' has no read request -- configuration is changing or bridge having invalid configuration?", bridge.getUID(), bridge.getLabel());
                updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, String.format("Poller %s '%s' has no poll task", bridge.getUID(), bridge.getLabel()));
                return;
            }
            readRequest = localReadRequest;
            slaveId = localReadRequest.getUnitID();
            functionCode = localReadRequest.getFunctionCode();
            comms = localPollerHandler.getCommunicationInterface();
            pollStart = localReadRequest.getReference();
            childOfEndpoint = false;
        }
        validateAndParseReadParameters(localConfig);
        validateAndParseWriteParameters(localConfig);
        validateMustReadOrWrite();
        updateStatusIfChanged(ThingStatus.ONLINE);
    } catch (ModbusConfigurationException | EndpointNotInitializedException e) {
        logger.debug("Thing {} '{}' initialization error: {}", getThing().getUID(), getThing().getLabel(), e.getMessage());
        updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
    } finally {
        logger.trace("initialize() of thing {} '{}' finished", thing.getUID(), thing.getLabel());
    }
}
Also used : ModbusDataConfiguration(org.openhab.binding.modbus.internal.config.ModbusDataConfiguration) ModbusEndpointThingHandler(org.openhab.binding.modbus.handler.ModbusEndpointThingHandler) BridgeHandler(org.openhab.core.thing.binding.BridgeHandler) ModbusConfigurationException(org.openhab.binding.modbus.internal.ModbusConfigurationException) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) EndpointNotInitializedException(org.openhab.binding.modbus.handler.EndpointNotInitializedException) Bridge(org.openhab.core.thing.Bridge)

Example 7 with ModbusPollerThingHandler

use of org.openhab.binding.modbus.handler.ModbusPollerThingHandler in project openhab-addons by openhab.

the class ModbusHandlerFactory method createHandler.

@Override
@Nullable
protected ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();
    if (thingTypeUID.equals(THING_TYPE_MODBUS_TCP)) {
        logger.debug("createHandler Modbus tcp");
        return new ModbusTcpThingHandler((Bridge) thing, manager);
    } else if (thingTypeUID.equals(THING_TYPE_MODBUS_SERIAL)) {
        logger.debug("createHandler Modbus serial");
        return new ModbusSerialThingHandler((Bridge) thing, manager);
    } else if (thingTypeUID.equals(THING_TYPE_MODBUS_POLLER)) {
        logger.debug("createHandler Modbus poller");
        return new ModbusPollerThingHandler((Bridge) thing);
    } else if (thingTypeUID.equals(THING_TYPE_MODBUS_DATA)) {
        logger.debug("createHandler data");
        return new ModbusDataThingHandler(thing);
    }
    logger.error("createHandler for unknown thing type uid {}. Thing label was: {}", thing.getThingTypeUID(), thing.getLabel());
    return null;
}
Also used : ModbusDataThingHandler(org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler) ModbusTcpThingHandler(org.openhab.binding.modbus.internal.handler.ModbusTcpThingHandler) ThingTypeUID(org.openhab.core.thing.ThingTypeUID) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) ModbusSerialThingHandler(org.openhab.binding.modbus.internal.handler.ModbusSerialThingHandler) Bridge(org.openhab.core.thing.Bridge) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 8 with ModbusPollerThingHandler

use of org.openhab.binding.modbus.handler.ModbusPollerThingHandler in project openhab-addons by openhab.

the class ModbusDataHandlerTest method createPollerMock.

private Bridge createPollerMock(String pollerId, PollTask task) {
    final Bridge poller;
    ThingUID thingUID = new ThingUID(THING_TYPE_MODBUS_POLLER, pollerId);
    BridgeBuilder builder = BridgeBuilder.create(THING_TYPE_MODBUS_POLLER, thingUID).withLabel("label for " + pollerId);
    for (Entry<String, String> entry : CHANNEL_TO_ACCEPTED_TYPE.entrySet()) {
        String channelId = entry.getKey();
        String channelAcceptedType = entry.getValue();
        builder = builder.withChannel(ChannelBuilder.create(new ChannelUID(thingUID, channelId), channelAcceptedType).build());
    }
    poller = builder.build();
    poller.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, ""));
    ModbusPollerThingHandler mockHandler = Mockito.mock(ModbusPollerThingHandler.class);
    doReturn(task.getRequest()).when(mockHandler).getRequest();
    assert comms != null;
    doReturn(comms).when(mockHandler).getCommunicationInterface();
    doReturn(task.getEndpoint()).when(comms).getEndpoint();
    poller.setHandler(mockHandler);
    assertSame(poller.getHandler(), mockHandler);
    assertSame(((ModbusPollerThingHandler) poller.getHandler()).getCommunicationInterface().getEndpoint(), task.getEndpoint());
    assertSame(((ModbusPollerThingHandler) poller.getHandler()).getRequest(), task.getRequest());
    addThing(poller);
    return poller;
}
Also used : ChannelUID(org.openhab.core.thing.ChannelUID) ThingUID(org.openhab.core.thing.ThingUID) ThingStatusInfo(org.openhab.core.thing.ThingStatusInfo) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) Bridge(org.openhab.core.thing.Bridge) BridgeBuilder(org.openhab.core.thing.binding.builder.BridgeBuilder)

Example 9 with ModbusPollerThingHandler

use of org.openhab.binding.modbus.handler.ModbusPollerThingHandler in project openhab-addons by openhab.

the class ModbusPollerThingHandlerTest method testRefreshWithPreviousData2.

/**
 * Testing again caching, such that most recently received data is propagated to children
 *
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws InterruptedException
 */
@Test
public void testRefreshWithPreviousData2() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, InterruptedException {
    Configuration pollerConfig = new Configuration();
    pollerConfig.put("refresh", 0L);
    pollerConfig.put("start", 5);
    pollerConfig.put("length", 13);
    pollerConfig.put("type", "coil");
    pollerConfig.put("cacheMillis", 10000L);
    poller = createPollerThingBuilder("poller").withConfiguration(pollerConfig).withBridge(endpoint.getUID()).build();
    addThing(poller);
    verifyEndpointBasicInitInteraction();
    ModbusPollerThingHandler thingHandler = (ModbusPollerThingHandler) poller.getHandler();
    assertNotNull(thingHandler);
    ModbusDataThingHandler child1 = Mockito.mock(ModbusDataThingHandler.class);
    thingHandler.childHandlerInitialized(child1, Mockito.mock(Thing.class));
    assertThat(poller.getStatus(), is(equalTo(ThingStatus.ONLINE)));
    verify(comms, never()).submitOneTimePoll(any(), any(), any());
    // data is received
    ModbusReadCallback pollerReadCallback = getPollerCallback(thingHandler);
    ModbusFailureCallback<ModbusReadRequestBlueprint> failureCallback = getPollerFailureCallback(thingHandler);
    ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
    ModbusReadRequestBlueprint request2 = Mockito.mock(ModbusReadRequestBlueprint.class);
    ModbusRegisterArray registers = Mockito.mock(ModbusRegisterArray.class);
    Exception error = Mockito.mock(Exception.class);
    AsyncModbusReadResult registersResult = new AsyncModbusReadResult(request, registers);
    AsyncModbusFailure<ModbusReadRequestBlueprint> errorResult = new AsyncModbusFailure<ModbusReadRequestBlueprint>(request2, error);
    pollerReadCallback.handle(registersResult);
    // data child should receive the data
    verify(child1).onReadResult(registersResult);
    verifyNoMoreInteractions(child1);
    reset(child1);
    // Sleep to have time between the data
    Thread.sleep(5L);
    // error is received
    failureCallback.handle(errorResult);
    // data child should receive the error
    verify(child1).handleReadError(errorResult);
    verifyNoMoreInteractions(child1);
    reset(child1);
    // call refresh, should return latest data (that is, error)
    // cache is still valid, we should not have real data poll this time
    thingHandler.refresh();
    verify(comms, never()).submitOneTimePoll(any(), any(), any());
    // data child receives the cached error
    verify(child1).handleReadError(errorResult);
    verifyNoMoreInteractions(child1);
}
Also used : ModbusDataThingHandler(org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler) ModbusRegisterArray(org.openhab.core.io.transport.modbus.ModbusRegisterArray) Configuration(org.openhab.core.config.core.Configuration) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) ModbusReadCallback(org.openhab.core.io.transport.modbus.ModbusReadCallback) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) AsyncModbusReadResult(org.openhab.core.io.transport.modbus.AsyncModbusReadResult) AsyncModbusFailure(org.openhab.core.io.transport.modbus.AsyncModbusFailure) Thing(org.openhab.core.thing.Thing) Test(org.junit.jupiter.api.Test)

Example 10 with ModbusPollerThingHandler

use of org.openhab.binding.modbus.handler.ModbusPollerThingHandler in project openhab-addons by openhab.

the class ModbusPollerThingHandlerTest method testRefresh.

@Test
public void testRefresh() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
    Configuration pollerConfig = new Configuration();
    pollerConfig.put("refresh", 0L);
    pollerConfig.put("start", 5);
    pollerConfig.put("length", 13);
    pollerConfig.put("type", "coil");
    poller = createPollerThingBuilder("poller").withConfiguration(pollerConfig).withBridge(endpoint.getUID()).build();
    addThing(poller);
    verifyEndpointBasicInitInteraction();
    assertThat(poller.getStatus(), is(equalTo(ThingStatus.ONLINE)));
    verify(comms, never()).submitOneTimePoll(any(), any(), any());
    ModbusPollerThingHandler thingHandler = (ModbusPollerThingHandler) poller.getHandler();
    assertNotNull(thingHandler);
    thingHandler.refresh();
    verify(comms).submitOneTimePoll(any(), any(), any());
}
Also used : Configuration(org.openhab.core.config.core.Configuration) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) Test(org.junit.jupiter.api.Test)

Aggregations

ModbusPollerThingHandler (org.openhab.binding.modbus.handler.ModbusPollerThingHandler)14 ModbusReadRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint)9 Test (org.junit.jupiter.api.Test)8 ModbusDataThingHandler (org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler)8 Configuration (org.openhab.core.config.core.Configuration)8 Thing (org.openhab.core.thing.Thing)8 AsyncModbusReadResult (org.openhab.core.io.transport.modbus.AsyncModbusReadResult)7 ModbusReadCallback (org.openhab.core.io.transport.modbus.ModbusReadCallback)7 ModbusRegisterArray (org.openhab.core.io.transport.modbus.ModbusRegisterArray)6 Bridge (org.openhab.core.thing.Bridge)4 ModbusDataConfiguration (org.openhab.binding.modbus.internal.config.ModbusDataConfiguration)3 AsyncModbusFailure (org.openhab.core.io.transport.modbus.AsyncModbusFailure)3 Nullable (org.eclipse.jdt.annotation.Nullable)2 EndpointNotInitializedException (org.openhab.binding.modbus.handler.EndpointNotInitializedException)2 ModbusEndpointThingHandler (org.openhab.binding.modbus.handler.ModbusEndpointThingHandler)2 ModbusConfigurationException (org.openhab.binding.modbus.internal.ModbusConfigurationException)2 BitArray (org.openhab.core.io.transport.modbus.BitArray)2 ModbusWriteRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint)2 PollTask (org.openhab.core.io.transport.modbus.PollTask)2 BridgeHandler (org.openhab.core.thing.binding.BridgeHandler)2