Search in sources :

Example 26 with ItemChannelLink

use of org.openhab.core.thing.link.ItemChannelLink in project openhab-core by openhab.

the class ThingManagerOSGiTest method thingManagerDoesNotDelegateUpdateEventsToItsSource.

@Test
public void thingManagerDoesNotDelegateUpdateEventsToItsSource() {
    registerThingTypeProvider();
    class ThingHandlerState {

        boolean handleCommandWasCalled;

        @Nullable
        ThingHandlerCallback callback;
    }
    final ThingHandlerState state = new ThingHandlerState();
    ThingHandler thingHandler = mock(ThingHandler.class);
    doAnswer(new Answer<Void>() {

        @Override
        @Nullable
        public Void answer(InvocationOnMock invocation) throws Throwable {
            state.callback = (ThingHandlerCallback) invocation.getArgument(0);
            return null;
        }
    }).when(thingHandler).setCallback(any(ThingHandlerCallback.class));
    doAnswer(new Answer<Void>() {

        @Override
        @Nullable
        public Void answer(InvocationOnMock invocation) throws Throwable {
            state.handleCommandWasCalled = true;
            state.callback.statusUpdated(thing, ThingStatusInfoBuilder.create(ThingStatus.ONLINE).build());
            return null;
        }
    }).when(thingHandler).handleCommand(any(ChannelUID.class), any(Command.class));
    when(thingHandler.getThing()).thenReturn(thing);
    ThingHandlerFactory thingHandlerFactory = mock(ThingHandlerFactory.class);
    when(thingHandlerFactory.supportsThingType(any(ThingTypeUID.class))).thenReturn(true);
    when(thingHandlerFactory.registerHandler(any(Thing.class))).thenReturn(thingHandler);
    String itemName = "name";
    managedThingProvider.add(thing);
    managedItemChannelLinkProvider.add(new ItemChannelLink(itemName, CHANNEL_UID));
    registerService(thingHandlerFactory);
    Item item = new StringItem(itemName);
    itemRegistry.add(item);
    waitForAssert(() -> assertThat(itemRegistry.get(itemName), is(notNullValue())));
    state.callback.statusUpdated(thing, ThingStatusInfoBuilder.create(ThingStatus.ONLINE).build());
    // event should be delivered
    eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, OnOffType.ON));
    waitForAssert(() -> assertThat(state.handleCommandWasCalled, is(true)));
    state.handleCommandWasCalled = false;
    // event should not be delivered, because the source is the same
    eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, OnOffType.ON, CHANNEL_UID.toString()));
    waitFor(() -> state.handleCommandWasCalled);
    assertThat(state.handleCommandWasCalled, is(false));
}
Also used : ItemChannelLink(org.openhab.core.thing.link.ItemChannelLink) ThingHandlerCallback(org.openhab.core.thing.binding.ThingHandlerCallback) ThingHandler(org.openhab.core.thing.binding.ThingHandler) ThingHandlerFactory(org.openhab.core.thing.binding.ThingHandlerFactory) StringItem(org.openhab.core.library.items.StringItem) Item(org.openhab.core.items.Item) StringItem(org.openhab.core.library.items.StringItem) Command(org.openhab.core.types.Command) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ChannelUID(org.openhab.core.thing.ChannelUID) ThingTypeUID(org.openhab.core.thing.ThingTypeUID) Nullable(org.eclipse.jdt.annotation.Nullable) Thing(org.openhab.core.thing.Thing) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 27 with ItemChannelLink

use of org.openhab.core.thing.link.ItemChannelLink in project openhab-core by openhab.

the class AutoUpdateManager method shouldAutoUpdate.

private Recommendation shouldAutoUpdate(Item item) {
    String itemName = item.getName();
    Recommendation ret = Recommendation.REQUIRED;
    // check if the item is a group item
    if (item instanceof GroupItem) {
        return Recommendation.DONT;
    }
    List<ChannelUID> linkedChannelUIDs = new ArrayList<>();
    for (ItemChannelLink link : itemChannelLinkRegistry.getLinks(itemName)) {
        linkedChannelUIDs.add(link.getLinkedUID());
    }
    // check if there is any channel ONLINE
    List<ChannelUID> onlineChannelUIDs = new ArrayList<>();
    for (ChannelUID channelUID : linkedChannelUIDs) {
        Thing thing = thingRegistry.get(channelUID.getThingUID());
        if (// 
        thing == null || // 
        thing.getChannel(channelUID.getId()) == null || // 
        thing.getHandler() == null || // 
        !ThingStatus.ONLINE.equals(thing.getStatus())) {
            continue;
        }
        onlineChannelUIDs.add(channelUID);
    }
    if (!linkedChannelUIDs.isEmpty() && onlineChannelUIDs.isEmpty()) {
        // none of the linked channels is able to process the command
        return Recommendation.REVERT;
    }
    for (ChannelUID channelUID : onlineChannelUIDs) {
        Thing thing = thingRegistry.get(channelUID.getThingUID());
        if (thing == null) {
            continue;
        }
        AutoUpdatePolicy policy = AutoUpdatePolicy.DEFAULT;
        Channel channel = thing.getChannel(channelUID.getId());
        if (channel != null) {
            AutoUpdatePolicy channelpolicy = channel.getAutoUpdatePolicy();
            if (channelpolicy != null) {
                policy = channelpolicy;
            } else {
                ChannelType channelType = channelTypeRegistry.getChannelType(channel.getChannelTypeUID());
                if (channelType != null && channelType.getAutoUpdatePolicy() != null) {
                    policy = channelType.getAutoUpdatePolicy();
                }
            }
        }
        switch(policy) {
            case VETO:
                ret = Recommendation.DONT;
                break;
            case DEFAULT:
                if (ret == Recommendation.REQUIRED || ret == Recommendation.RECOMMENDED) {
                    ret = Recommendation.OPTIMISTIC;
                }
                break;
            case RECOMMEND:
                if (ret == Recommendation.REQUIRED) {
                    ret = Recommendation.RECOMMENDED;
                }
                break;
        }
    }
    return ret;
}
Also used : AutoUpdatePolicy(org.openhab.core.thing.type.AutoUpdatePolicy) ChannelUID(org.openhab.core.thing.ChannelUID) Channel(org.openhab.core.thing.Channel) ArrayList(java.util.ArrayList) ItemChannelLink(org.openhab.core.thing.link.ItemChannelLink) GroupItem(org.openhab.core.items.GroupItem) ChannelType(org.openhab.core.thing.type.ChannelType) Thing(org.openhab.core.thing.Thing)

Example 28 with ItemChannelLink

use of org.openhab.core.thing.link.ItemChannelLink in project openhab-core by openhab.

the class ItemChannelLinkResource method unlink.

@DELETE
@RolesAllowed({ Role.ADMIN })
@Path("/{itemName}/{channelUID}")
@Operation(operationId = "unlinkItemFromChannel", summary = "Unlinks an item from a channel.", security = { @SecurityRequirement(name = "oauth2", scopes = { "admin" }) }, responses = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "Link not found."), @ApiResponse(responseCode = "405", description = "Link not editable.") })
public Response unlink(@PathParam("itemName") @Parameter(description = "itemName") String itemName, @PathParam("channelUID") @Parameter(description = "channelUID") String channelUid) {
    ChannelUID uid;
    try {
        uid = new ChannelUID(channelUid);
    } catch (IllegalArgumentException e) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    String linkId = AbstractLink.getIDFor(itemName, uid);
    if (itemChannelLinkRegistry.get(linkId) == null) {
        String message = "Link " + linkId + " does not exist!";
        return JSONResponse.createResponse(Status.NOT_FOUND, null, message);
    }
    ItemChannelLink result = itemChannelLinkRegistry.remove(linkId);
    if (result == null) {
        return Response.status(Status.METHOD_NOT_ALLOWED).build();
    }
    return Response.ok(null, MediaType.TEXT_PLAIN).build();
}
Also used : ChannelUID(org.openhab.core.thing.ChannelUID) ItemChannelLink(org.openhab.core.thing.link.ItemChannelLink) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) RolesAllowed(javax.annotation.security.RolesAllowed) Operation(io.swagger.v3.oas.annotations.Operation)

Example 29 with ItemChannelLink

use of org.openhab.core.thing.link.ItemChannelLink in project openhab-core by openhab.

the class ItemChannelLinkResource method link.

@PUT
@RolesAllowed({ Role.ADMIN })
@Path("/{itemName}/{channelUID}")
@Consumes(MediaType.APPLICATION_JSON)
@Operation(operationId = "linkItemToChannel", summary = "Links an item to a channel.", security = { @SecurityRequirement(name = "oauth2", scopes = { "admin" }) }, responses = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Content does not match the path"), @ApiResponse(responseCode = "405", description = "Link is not editable") })
public Response link(@PathParam("itemName") @Parameter(description = "itemName") String itemName, @PathParam("channelUID") @Parameter(description = "channelUID") String channelUid, @Parameter(description = "link data") @Nullable ItemChannelLinkDTO bean) {
    ChannelUID uid;
    try {
        uid = new ChannelUID(channelUid);
    } catch (IllegalArgumentException e) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    ItemChannelLink link;
    if (bean == null) {
        link = new ItemChannelLink(itemName, uid, new Configuration());
    } else {
        if (bean.channelUID != null && !bean.channelUID.equals(channelUid)) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (bean.itemName != null && !bean.itemName.equals(itemName)) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        link = new ItemChannelLink(itemName, uid, new Configuration(bean.configuration));
    }
    if (itemChannelLinkRegistry.get(link.getUID()) == null) {
        itemChannelLinkRegistry.add(link);
    } else {
        ItemChannelLink oldLink = itemChannelLinkRegistry.update(link);
        if (oldLink == null) {
            return Response.status(Status.METHOD_NOT_ALLOWED).build();
        }
    }
    return Response.ok(null, MediaType.TEXT_PLAIN).build();
}
Also used : Configuration(org.openhab.core.config.core.Configuration) ChannelUID(org.openhab.core.thing.ChannelUID) ItemChannelLink(org.openhab.core.thing.link.ItemChannelLink) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) Consumes(javax.ws.rs.Consumes) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Example 30 with ItemChannelLink

use of org.openhab.core.thing.link.ItemChannelLink in project openhab-core by openhab.

the class GenericItemChannelLinkProviderJavaTest method testLinkConfiguration.

@Test
public void testLinkConfiguration() {
    Collection<Thing> things = thingRegistry.getAll();
    assertThat(things.size(), is(0));
    String thingsModel = "Bridge hue:bridge:huebridge [ ipAddress = \"192.168.3.84\", userName = \"19fc3fa6fc870a4280a55f21315631f\" ] {" + // 
    "LCT001 bulb3 [ lightId = \"3\" ]" + // 
    "LCT001 bulb4 [ lightId = \"3\" ]" + "}";
    modelRepository.addOrRefreshModel(THINGS_TESTMODEL_NAME, new ByteArrayInputStream(thingsModel.getBytes()));
    waitForAssert(() -> {
        assertThat(thingRegistry.getAll().size(), is(3));
    });
    String itemsModel = "Color Light3Color \"Light3 Color\" { channel=\"hue:LCT001:huebridge:bulb3:color\" [ foo=\"bar\", answer=42, always=true ] }" + "Group:Switch:MAX TestSwitches";
    modelRepository.addOrRefreshModel(ITEMS_TESTMODEL_NAME, new ByteArrayInputStream(itemsModel.getBytes()));
    waitForAssert(() -> {
        assertThat(itemRegistry.getItems().size(), is(2));
        assertThat(itemChannelLinkRegistry.getAll().size(), is(1));
    });
    ItemChannelLink link = itemChannelLinkRegistry.get("Light3Color -> hue:LCT001:huebridge:bulb3:color");
    assertNotNull(link);
    assertEquals("Light3Color", link.getItemName());
    assertEquals("hue:LCT001:huebridge:bulb3:color", link.getLinkedUID().toString());
    assertEquals("bar", link.getConfiguration().get("foo"));
    assertEquals(new BigDecimal(42), link.getConfiguration().get("answer"));
    assertEquals(true, link.getConfiguration().get("always"));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ItemChannelLink(org.openhab.core.thing.link.ItemChannelLink) Thing(org.openhab.core.thing.Thing) BigDecimal(java.math.BigDecimal) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Aggregations

ItemChannelLink (org.openhab.core.thing.link.ItemChannelLink)49 Test (org.junit.jupiter.api.Test)30 Thing (org.openhab.core.thing.Thing)14 Item (org.openhab.core.items.Item)13 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)13 ChannelUID (org.openhab.core.thing.ChannelUID)11 StringItem (org.openhab.core.library.items.StringItem)8 ThingTypeUID (org.openhab.core.thing.ThingTypeUID)8 Configuration (org.openhab.core.config.core.Configuration)6 NumberItem (org.openhab.core.library.items.NumberItem)6 ThingUID (org.openhab.core.thing.ThingUID)6 Nullable (org.eclipse.jdt.annotation.Nullable)5 Channel (org.openhab.core.thing.Channel)5 ThingRegistry (org.openhab.core.thing.ThingRegistry)5 ThingHandler (org.openhab.core.thing.binding.ThingHandler)5 ThingHandlerCallback (org.openhab.core.thing.binding.ThingHandlerCallback)5 ManagedItemChannelLinkProvider (org.openhab.core.thing.link.ManagedItemChannelLinkProvider)5 ArrayList (java.util.ArrayList)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 ManagedThingProvider (org.openhab.core.thing.ManagedThingProvider)4