Search in sources :

Example 16 with ModbusDataThingHandler

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

the class ModbusDataHandlerTest method testWriteRealTransformation4.

@Test
public void testWriteRealTransformation4() throws InvalidSyntaxException {
    captureModbusWrites();
    mockTransformation("JSON", new TransformationService() {

        @Override
        public String transform(String function, String source) throws TransformationException {
            return // 
            "[{" + // 
            "\"functionCode\": 16," + // 
            "\"address\": 5412," + // 
            "\"value\": [1, 0, 5]" + // 
            "}," + // 
            "{" + // 
            "\"functionCode\": 6," + // 
            "\"address\": 555," + // 
            "\"value\": [3]" + "}]";
        }
    });
    ModbusDataThingHandler dataHandler = testWriteHandlingGeneric("50", "JSON(foobar)", ModbusConstants.ValueType.INT16, "holding", ModbusWriteFunctionCode.WRITE_MULTIPLE_REGISTERS, "number", new DecimalType("2"), null, bundleContext);
    assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_SUCCESS, is(notNullValue(State.class)));
    assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_ERROR, is(nullValue(State.class)));
    assertThat(writeRequests.size(), is(equalTo(2)));
    {
        ModbusWriteRequestBlueprint writeRequest = writeRequests.get(0);
        assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_MULTIPLE_REGISTERS)));
        assertThat(writeRequest.getReference(), is(equalTo(5412)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().size(), is(equalTo(3)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(0), is(equalTo(1)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(1), is(equalTo(0)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(2), is(equalTo(5)));
    }
    {
        ModbusWriteRequestBlueprint writeRequest = writeRequests.get(1);
        assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_SINGLE_REGISTER)));
        assertThat(writeRequest.getReference(), is(equalTo(555)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().size(), is(equalTo(1)));
        assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(0), is(equalTo(3)));
    }
}
Also used : ModbusDataThingHandler(org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler) TransformationException(org.openhab.core.transform.TransformationException) ModbusWriteRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint) DecimalType(org.openhab.core.library.types.DecimalType) TransformationService(org.openhab.core.transform.TransformationService) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 17 with ModbusDataThingHandler

use of org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler 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 18 with ModbusDataThingHandler

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

the class ModbusPollerThingHandlerTest method testRefreshWithPreviousDataCacheDisabled.

/**
 * When there's no recently received data, refresh() will re-use that instead
 *
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws NoSuchFieldException
 * @throws SecurityException
 */
@Test
public void testRefreshWithPreviousDataCacheDisabled() 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");
    pollerConfig.put("cacheMillis", 0L);
    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);
    ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
    ModbusRegisterArray registers = Mockito.mock(ModbusRegisterArray.class);
    AsyncModbusReadResult result = new AsyncModbusReadResult(request, registers);
    pollerReadCallback.handle(result);
    // data child receives the data
    verify(child1).onReadResult(result);
    verifyNoMoreInteractions(child1);
    reset(child1);
    // call refresh
    // caching disabled, should poll from manager
    thingHandler.refresh();
    verify(comms).submitOneTimePoll(any(), any(), any());
    verifyNoMoreInteractions(mockedModbusManager);
    // data child receives the cached data
    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) Thing(org.openhab.core.thing.Thing) Test(org.junit.jupiter.api.Test)

Example 19 with ModbusDataThingHandler

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

the class ModbusPollerThingHandlerTest method testErrorPassedToChildDataThings.

@Test
public void testErrorPassedToChildDataThings() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
    PollTask pollTask = Mockito.mock(PollTask.class);
    doReturn(pollTask).when(comms).registerRegularPoll(notNull(), eq(150l), eq(0L), notNull(), notNull());
    Configuration pollerConfig = new Configuration();
    pollerConfig.put("refresh", 150L);
    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)));
    final ArgumentCaptor<ModbusFailureCallback<ModbusReadRequestBlueprint>> callbackCapturer = ArgumentCaptor.forClass((Class) ModbusFailureCallback.class);
    verify(comms).registerRegularPoll(any(), eq(150l), eq(0L), notNull(), callbackCapturer.capture());
    ModbusFailureCallback<ModbusReadRequestBlueprint> readCallback = callbackCapturer.getValue();
    assertNotNull(readCallback);
    ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
    Exception error = Mockito.mock(Exception.class);
    ModbusPollerThingHandler thingHandler = (ModbusPollerThingHandler) poller.getHandler();
    assertNotNull(thingHandler);
    ModbusDataThingHandler child1 = Mockito.mock(ModbusDataThingHandler.class);
    ModbusDataThingHandler child2 = Mockito.mock(ModbusDataThingHandler.class);
    AsyncModbusFailure<ModbusReadRequestBlueprint> result = new AsyncModbusFailure<ModbusReadRequestBlueprint>(request, error);
    // has one data child
    thingHandler.childHandlerInitialized(child1, Mockito.mock(Thing.class));
    readCallback.handle(result);
    verify(child1).handleReadError(result);
    verifyNoMoreInteractions(child1);
    verifyNoMoreInteractions(child2);
    reset(child1);
    // two children (one child initialized)
    thingHandler.childHandlerInitialized(child2, Mockito.mock(Thing.class));
    readCallback.handle(result);
    verify(child1).handleReadError(result);
    verify(child2).handleReadError(result);
    verifyNoMoreInteractions(child1);
    verifyNoMoreInteractions(child2);
    reset(child1);
    reset(child2);
    // one child disposed
    thingHandler.childHandlerDisposed(child1, Mockito.mock(Thing.class));
    readCallback.handle(result);
    verify(child2).handleReadError(result);
    verifyNoMoreInteractions(child1);
    verifyNoMoreInteractions(child2);
}
Also used : ModbusDataThingHandler(org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler) PollTask(org.openhab.core.io.transport.modbus.PollTask) Configuration(org.openhab.core.config.core.Configuration) ModbusFailureCallback(org.openhab.core.io.transport.modbus.ModbusFailureCallback) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) AsyncModbusFailure(org.openhab.core.io.transport.modbus.AsyncModbusFailure) Thing(org.openhab.core.thing.Thing) Test(org.junit.jupiter.api.Test)

Example 20 with ModbusDataThingHandler

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

the class ModbusDataHandlerTest method createDataHandler.

private ModbusDataThingHandler createDataHandler(String id, Bridge bridge, Function<ThingBuilder, ThingBuilder> builderConfigurator, BundleContext context, boolean autoCreateItemsAndLinkToChannels) {
    ThingUID thingUID = new ThingUID(THING_TYPE_MODBUS_DATA, id);
    ThingBuilder builder = ThingBuilder.create(THING_TYPE_MODBUS_DATA, thingUID).withLabel("label for " + id);
    Map<String, ChannelUID> toBeLinked = new HashMap<>();
    for (Entry<String, String> entry : CHANNEL_TO_ACCEPTED_TYPE.entrySet()) {
        String channelId = entry.getKey();
        // accepted item type
        String channelAcceptedType = entry.getValue();
        ChannelUID channelUID = new ChannelUID(thingUID, channelId);
        builder = builder.withChannel(ChannelBuilder.create(channelUID, channelAcceptedType).build());
        if (autoCreateItemsAndLinkToChannels) {
            // Create item of correct type and link it to channel
            String itemName = getItemName(channelUID);
            final GenericItem item;
            item = coreItemFactory.createItem(channelAcceptedType, itemName);
            assertThat(String.format("Could not determine correct item type for %s", channelId), item, is(notNullValue()));
            assertNotNull(item);
            Objects.requireNonNull(item);
            addItem(item);
            toBeLinked.put(itemName, channelUID);
        }
    }
    if (builderConfigurator != null) {
        builder = builderConfigurator.apply(builder);
    }
    Thing dataThing = builder.withBridge(bridge.getUID()).build();
    addThing(dataThing);
    // Link after the things and items have been created
    for (Entry<String, ChannelUID> entry : toBeLinked.entrySet()) {
        linkItem(entry.getKey(), entry.getValue());
    }
    return (ModbusDataThingHandler) dataThing.getHandler();
}
Also used : ModbusDataThingHandler(org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler) ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) GenericItem(org.openhab.core.items.GenericItem) HashMap(java.util.HashMap) ChannelUID(org.openhab.core.thing.ChannelUID) ThingUID(org.openhab.core.thing.ThingUID) Thing(org.openhab.core.thing.Thing)

Aggregations

ModbusDataThingHandler (org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler)27 Test (org.junit.jupiter.api.Test)19 ModbusReadRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint)14 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)13 Configuration (org.openhab.core.config.core.Configuration)13 ModbusRegisterArray (org.openhab.core.io.transport.modbus.ModbusRegisterArray)10 ModbusWriteRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint)10 PollTask (org.openhab.core.io.transport.modbus.PollTask)9 ModbusPollerThingHandler (org.openhab.binding.modbus.handler.ModbusPollerThingHandler)8 AsyncModbusReadResult (org.openhab.core.io.transport.modbus.AsyncModbusReadResult)8 DecimalType (org.openhab.core.library.types.DecimalType)8 Bridge (org.openhab.core.thing.Bridge)8 Thing (org.openhab.core.thing.Thing)8 ModbusWriteCoilRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusWriteCoilRequestBlueprint)7 ModbusSlaveEndpoint (org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint)7 ModbusTCPSlaveEndpoint (org.openhab.core.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint)7 ModbusReadCallback (org.openhab.core.io.transport.modbus.ModbusReadCallback)6 ModbusWriteRegisterRequestBlueprint (org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint)6 TransformationException (org.openhab.core.transform.TransformationException)6 TransformationService (org.openhab.core.transform.TransformationService)5