Java Code Examples for org.eclipse.smarthome.core.thing.Thing#getHandler()

The following examples show how to use org.eclipse.smarthome.core.thing.Thing#getHandler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BridgeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void handleRemoval() {
    for (Thing thing : getThing().getThings()) {
        // Inform Thing-Child's about removed bridge.
        final ThingHandler thingHandler = thing.getHandler();
        if (thingHandler != null) {
            thingHandler.bridgeStatusChanged(ThingStatusInfoBuilder.create(ThingStatus.REMOVED).build());
        }
    }
    if (StringUtils.isNotBlank((String) super.getConfig().get(APPLICATION_TOKEN))) {
        if (connMan == null) {
            Config config = loadAndCheckConnectionData(this.getConfig());
            if (config != null) {
                this.connMan = new ConnectionManagerImpl(config, null, false);
            } else {
                updateStatus(ThingStatus.REMOVED);
                return;
            }
        }
        if (connMan.removeApplicationToken()) {
            logger.debug("Application-Token deleted");
        }
    }
    updateStatus(ThingStatus.REMOVED);
}
 
Example 2
Source File: ThingStatusInfoI18nLocalizationService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Localizes the {@link ThingStatusInfo} for the given thing.
 *
 * @param thing the thing whose thing status info is to be localized (must not be null)
 * @param locale the locale to be used (can be null)
 * @return the localized thing status or the original thing status if
 *         <ul>
 *         <li>there is nothing to be localized</li>
 *         <li>the thing does not have a handler</li>
 *         </ul>
 * @throws IllegalArgumentException if given thing is null
 */
public ThingStatusInfo getLocalizedThingStatusInfo(Thing thing, Locale locale) {
    if (thing == null) {
        throw new IllegalArgumentException("Thing must not be null.");
    }

    ThingHandler thingHandler = thing.getHandler();

    if (thingHandler == null) {
        return thing.getStatusInfo();
    }

    String description = thing.getStatusInfo().getDescription();
    if (description == null || !I18nUtil.isConstant(description)) {
        return thing.getStatusInfo();
    }

    String translatedDescription = translateDescription(description, locale, thingHandler);

    return new ThingStatusInfo(thing.getStatus(), thing.getStatusInfo().getStatusDetail(), translatedDescription);
}
 
Example 3
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void saveAllPlayerState() {
    Collection<Thing> allThings = thingRegistry.getAll();
    for (Thing aThing : allThings) {
        if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
            ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
            if (handler != null) {
                handler.saveState();
            }
        }
    }
}
 
Example 4
Source File: ThingActionService.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public static ThingActions getActions(String scope, String thingUid) {
    ThingUID uid = new ThingUID(thingUid);
    Thing thing = thingRegistry.get(uid);
    if (thing != null) {
        ThingHandler handler = thing.getHandler();
        if (handler != null) {
            ThingActions thingActions = thingActionsMap.get(getKey(scope, thingUid));
            return thingActions;
        }
    }
    return null;
}
 
Example 5
Source File: HomematicBridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onStateUpdated(HmDatapoint dp) {
    Thing hmThing = getThingByUID(UidUtils.generateThingUID(dp.getChannel().getDevice(), getThing()));
    if (hmThing != null) {
        final ThingStatus status = hmThing.getStatus();
        if (status == ThingStatus.ONLINE || status == ThingStatus.OFFLINE) {
            HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
            if (thingHandler != null) {
                thingHandler.updateDatapointState(dp);
            }
        }
    }
}
 
Example 6
Source File: HomematicBridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates the thing for the given Homematic device.
 */
private void updateThing(HmDevice device) {
    Thing hmThing = getThingByUID(UidUtils.generateThingUID(device, getThing()));
    if (hmThing != null) {
        HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
        if (thingHandler != null) {
            thingHandler.thingUpdated(hmThing);
            for (Channel channel : hmThing.getChannels()) {
                thingHandler.handleRefresh(channel.getUID());
            }
        }
    }
}
 
Example 7
Source File: HomematicBridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the OFFLINE status for all things of this bridge that has been removed from the gateway.
 */
@SuppressWarnings("null")
public void setOfflineStatus() {
    for (Thing hmThing : getThing().getThings()) {
        try {
            gateway.getDevice(UidUtils.getHomematicAddress(hmThing));
        } catch (HomematicClientException e) {
            if (hmThing.getHandler() != null) {
                ((HomematicThingHandler) hmThing.getHandler()).handleRemoval();
            }
        }
    }
}
 
Example 8
Source File: WemoMakerHandlerOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertThatThingHandlesREFRESHCommand()
        throws MalformedURLException, URISyntaxException, ValidationException {
    Command command = RefreshType.REFRESH;

    WemoHttpCall mockCaller = Mockito.spy(new WemoHttpCall());
    Thing thing = createThing(THING_TYPE_UID, DEFAULT_TEST_CHANNEL, DEFAULT_TEST_CHANNEL_TYPE, mockCaller);

    waitForAssert(() -> {
        assertThat(thing.getStatus(), is(ThingStatus.ONLINE));
    });

    // The Device is registered as UPnP Device after the initialization, this will ensure that the polling job will
    // not start
    addUpnpDevice(BASIC_EVENT_SERVICE_ID, SERVICE_NUMBER, MODEL);

    ChannelUID channelUID = new ChannelUID(thing.getUID(), DEFAULT_TEST_CHANNEL);
    ThingHandler handler = thing.getHandler();
    assertNotNull(handler);
    handler.handleCommand(channelUID, command);

    ArgumentCaptor<String> captur = ArgumentCaptor.forClass(String.class);
    verify(mockCaller, atLeastOnce()).executeCall(any(), any(), captur.capture());

    List<String> results = captur.getAllValues();
    boolean found = false;
    for (String result : results) {
        if (result.contains("<u:GetAttributes xmlns:u=\"urn:Belkin:service:deviceevent:1\"></u:GetAttributes>")) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example 9
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void restoreAllPlayerState() {
    Collection<Thing> allThings = thingRegistry.getAll();
    for (Thing aThing : allThings) {
        if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
            ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
            if (handler != null) {
                handler.restoreState();
            }
        }
    }
}
 
Example 10
Source File: WemoHandlerOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertThatThingHandlesREFRESHCommandCorrectly()
        throws MalformedURLException, URISyntaxException, ValidationException {
    Command command = RefreshType.REFRESH;

    WemoHttpCall mockCaller = Mockito.spy(new WemoHttpCall());
    Thing thing = createThing(THING_TYPE_UID, DEFAULT_TEST_CHANNEL, DEFAULT_TEST_CHANNEL_TYPE, mockCaller);

    waitForAssert(() -> {
        assertThat(thing.getStatus(), is(ThingStatus.ONLINE));
    });

    // The device is registered as UPnP Device after the initialization, this will ensure that the polling job will
    // not start
    addUpnpDevice(SERVICE_ID, SERVICE_NUMBER, MODEL_NAME);

    WemoHandler handler = (WemoHandler) thing.getHandler();
    assertNotNull(handler);

    ChannelUID channelUID = new ChannelUID(thing.getUID(), DEFAULT_TEST_CHANNEL);
    handler.handleCommand(channelUID, command);

    ArgumentCaptor<String> captur = ArgumentCaptor.forClass(String.class);

    verify(mockCaller, atLeastOnce()).executeCall(any(), any(), captur.capture());

    List<String> results = captur.getAllValues();
    boolean found = false;
    for (String result : results) {
        if (result.contains("<u:GetBinaryState xmlns:u=\"urn:Belkin:service:basicevent:1\"></u:GetBinaryState>")) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example 11
Source File: AbstractDmxThingTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertThingStatus(Thing thing) {
    // check that thing turns online if properly configured
    waitForAssert(() -> assertEquals(ThingStatus.ONLINE, thing.getStatusInfo().getStatus()));

    // check that thing properly follows bridge status
    ThingHandler handler = thing.getHandler();
    assertNotNull(handler);
    handler.bridgeStatusChanged(ThingStatusInfoBuilder.create(ThingStatus.OFFLINE).build());
    waitForAssert(() -> assertEquals(ThingStatus.OFFLINE, thing.getStatusInfo().getStatus()));
    handler.bridgeStatusChanged(ThingStatusInfoBuilder.create(ThingStatus.ONLINE).build());
    waitForAssert(() -> assertEquals(ThingStatus.ONLINE, thing.getStatusInfo().getStatus()));
}
 
Example 12
Source File: HomematicBridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("null")
@Override
public void onDeviceDeleted(HmDevice device) {
    discoveryService.deviceRemoved(device);
    updateThing(device);

    Thing hmThing = getThingByUID(UidUtils.generateThingUID(device, getThing()));
    if (hmThing != null && hmThing.getHandler() != null) {
        ((HomematicThingHandler) hmThing.getHandler()).deviceRemoved();
    }
}
 
Example 13
Source File: ProfileCallbackImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleUpdate(State state) {
    Thing thing = thingProvider.apply(link.getLinkedUID().getThingUID());
    if (thing != null) {
        final ThingHandler handler = thing.getHandler();
        if (handler != null) {
            if (ThingHandlerHelper.isHandlerInitialized(thing)) {
                logger.debug("Delegating update '{}' for item '{}' to handler for channel '{}'", state,
                        link.getItemName(), link.getLinkedUID());
                safeCaller.create(handler, ThingHandler.class)
                        .withTimeout(CommunicationManager.THINGHANDLER_EVENT_TIMEOUT).onTimeout(() -> {
                            logger.warn("Handler for thing '{}' takes more than {}ms for handling an update",
                                    handler.getThing().getUID(), CommunicationManager.THINGHANDLER_EVENT_TIMEOUT);
                        }).build().handleUpdate(link.getLinkedUID(), state);
            } else {
                logger.debug("Not delegating update '{}' for item '{}' to handler for channel '{}', "
                        + "because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE but was {}).",
                        state, link.getItemName(), link.getLinkedUID(), thing.getStatus());
            }
        } else {
            logger.warn("Cannot delegate update '{}' for item '{}' to handler for channel '{}', "
                    + "because no handler is assigned. Maybe the binding is not installed or not "
                    + "propertly initialized.", state, link.getItemName(), link.getLinkedUID());
        }
    } else {
        logger.warn(
                "Cannot delegate update '{}' for item '{}' to handler for channel '{}', "
                        + "because no thing with the UID '{}' could be found.",
                state, link.getItemName(), link.getLinkedUID(), link.getLinkedUID().getThingUID());
    }
}
 
Example 14
Source File: ProfileCallbackImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(Command command) {
    Thing thing = thingProvider.apply(link.getLinkedUID().getThingUID());
    if (thing != null) {
        final ThingHandler handler = thing.getHandler();
        if (handler != null) {
            if (ThingHandlerHelper.isHandlerInitialized(thing)) {
                logger.debug("Delegating command '{}' for item '{}' to handler for channel '{}'", command,
                        link.getItemName(), link.getLinkedUID());
                safeCaller.create(handler, ThingHandler.class)
                        .withTimeout(CommunicationManager.THINGHANDLER_EVENT_TIMEOUT).onTimeout(() -> {
                            logger.warn("Handler for thing '{}' takes more than {}ms for handling a command",
                                    handler.getThing().getUID(), CommunicationManager.THINGHANDLER_EVENT_TIMEOUT);
                        }).build().handleCommand(link.getLinkedUID(), command);
            } else {
                logger.debug("Not delegating command '{}' for item '{}' to handler for channel '{}', "
                        + "because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE but was {}).",
                        command, link.getItemName(), link.getLinkedUID(), thing.getStatus());
            }
        } else {
            logger.warn("Cannot delegate command '{}' for item '{}' to handler for channel '{}', "
                    + "because no handler is assigned. Maybe the binding is not installed or not "
                    + "propertly initialized.", command, link.getItemName(), link.getLinkedUID());
        }
    } else {
        logger.warn(
                "Cannot delegate command '{}' for item '{}' to handler for channel '{}', "
                        + "because no thing with the UID '{}' could be found.",
                command, link.getItemName(), link.getLinkedUID(), link.getLinkedUID().getThingUID());
    }
}
 
Example 15
Source File: ThingRegistryImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void updateConfiguration(ThingUID thingUID, Map<@NonNull String, Object> configurationParameters) {
    Thing thing = get(thingUID);
    if (thing != null) {
        ThingHandler thingHandler = thing.getHandler();
        if (thingHandler != null) {
            thingHandler.handleConfigurationUpdate(configurationParameters);
        } else {
            throw new IllegalStateException("Thing with UID " + thingUID + " has no handler attached.");
        }
    } else {
        throw new IllegalArgumentException("Thing with UID " + thingUID + " does not exists.");
    }
}
 
Example 16
Source File: BaseThingHandlerFactory.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void unregisterHandler(Thing thing) {
    ThingHandler thingHandler = thing.getHandler();
    if (thingHandler != null) {
        removeHandler(thingHandler);
        unsetBundleContext(thingHandler);
    }
    unregisterConfigStatusProvider(thing);
    unregisterFirmwareUpdateHandler(thing);
    unregisterServices(thing);
}
 
Example 17
Source File: BridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void setStatus(ThingStatus status) {
    logger.debug("set status to: {}", status);
    updateStatus(status);
    for (Thing thing : getThing().getThings()) {
        ThingHandler handler = thing.getHandler();
        if (handler != null) {
            handler.bridgeStatusChanged(getThing().getStatusInfo());
        }
    }
}
 
Example 18
Source File: ScriptThingActions.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets an actions instance of a certain scope for a given thing UID
 *
 * @param scope the action scope
 * @param thingUid the UID of the thing
 *
 * @return actions the actions instance or null, if not available
 */
public ThingActions get(String scope, String thingUid) {
    ThingUID uid = new ThingUID(thingUid);
    Thing thing = thingRegistry.get(uid);
    if (thing != null) {
        ThingHandler handler = thing.getHandler();
        if (handler != null) {
            ThingActions thingActions = thingActionsMap.get(getKey(scope, thingUid));
            return thingActions;
        }
    }
    return null;
}
 
Example 19
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private void initializeHandler(Thing thing) {
    if (isDisabledByStorage(thing.getUID())) {
        setThingStatus(thing, buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.DISABLED));
        logger.debug("Thing '{}' will not be initialized. It is marked as disabled.", thing.getUID());
        return;
    }
    if (!isHandlerRegistered(thing)) {
        return;
    }
    Lock lock = getLockForThing(thing.getUID());
    try {
        lock.lock();
        if (ThingHandlerHelper.isHandlerInitialized(thing)) {
            logger.debug("Attempt to initialize the already initialized thing '{}' will be ignored.",
                    thing.getUID());
            return;
        }
        if (isInitializing(thing)) {
            logger.debug("Attempt to initialize a handler twice for thing '{}' at the same time will be ignored.",
                    thing.getUID());
            return;
        }
        ThingHandler handler = thing.getHandler();
        if (handler == null) {
            throw new IllegalStateException("Handler should not be null here");
        } else {
            if (handler.getThing() != thing) {
                logger.warn("The model of {} is inconsistent [thing.getHandler().getThing() != thing]",
                        thing.getUID());
            }
        }
        ThingType thingType = getThingType(thing);
        applyDefaultConfiguration(thing, thingType);

        if (isInitializable(thing, thingType)) {
            setThingStatus(thing, buildStatusInfo(ThingStatus.INITIALIZING, ThingStatusDetail.NONE));
            doInitializeHandler(thing.getHandler());
        } else {
            logger.debug("Thing '{}' not initializable, check required configuration parameters.", thing.getUID());
            setThingStatus(thing,
                    buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.HANDLER_CONFIGURATION_PENDING));
        }
    } finally {
        lock.unlock();
    }
}
 
Example 20
Source File: WemoLightHandlerOSGiTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private void assertRequestForCommand(String channelID, Command command, String action, String value,
        String capitability) throws MalformedURLException, URISyntaxException, ValidationException {
    Thing bridge = createBridge(BRIDGE_TYPE_UID);

    WemoHttpCall mockCaller = Mockito.spy(new WemoHttpCall());
    Thing thing = createThing(THING_TYPE_UID, DEFAULT_TEST_CHANNEL, DEFAULT_TEST_CHANNEL_TYPE, mockCaller);

    waitForAssert(() -> {
        assertThat(bridge.getStatus(), is(ThingStatus.ONLINE));
    });

    waitForAssert(() -> {
        assertThat(thing.getStatus(), is(ThingStatus.ONLINE));
    });

    // The device is registered as UPnP Device after the initialization, this will ensure that the polling job will
    // not start
    addUpnpDevice(SERVICE_ID, SERVICE_NUMBER, DEVICE_MODEL_NAME);

    ThingUID thingUID = new ThingUID(THING_TYPE_UID, TEST_THING_ID);
    ChannelUID channelUID = new ChannelUID(thingUID, channelID);
    ThingHandler handler = thing.getHandler();
    assertNotNull(handler);
    handler.handleCommand(channelUID, command);

    ArgumentCaptor<String> captur = ArgumentCaptor.forClass(String.class);

    verify(mockCaller, atLeastOnce()).executeCall(any(), any(), captur.capture());

    List<String> results = captur.getAllValues();
    // we might catch multiple calls. iterate through them to find the one matching our settings
    boolean found = false;
    for (String result : results) {
        boolean matchesCapability = result.contains("CapabilityID&gt;" + capitability + "&lt;");
        boolean matchesValue = result.contains("CapabilityValue&gt;" + value + "&lt;");
        boolean matchesAction = result.contains("<s:Body><u:" + action);

        if (action != null) {
            if (matchesAction == false) {
                continue;
            }
        }
        if (capitability != null) {
            if (matchesCapability == false) {
                continue;
            }
        }
        if (value != null) {
            if (matchesValue == false) {
                continue;
            }
        }
        found = true;
        break;
    }
    assertTrue(found);
}