org.eclipse.smarthome.core.thing.binding.ThingHandler Java Examples

The following examples show how to use org.eclipse.smarthome.core.thing.binding.ThingHandler. 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: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void notifyThingHandlerAboutRemoval(final Thing thing) {
    logger.trace("Asking handler of thing '{}' to handle its removal.", thing.getUID());

    ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() {
        @Override
        public void run() {
            try {
                ThingHandler handler = thing.getHandler();
                if (handler != null) {
                    handler.handleRemoval();
                    logger.trace("Handler of thing '{}' returned from handling its removal.", thing.getUID());
                } else {
                    logger.trace("No handler of thing '{}' available, so deferring the removal call.",
                            thing.getUID());
                }
            } catch (Exception ex) {
                logger.error("The ThingHandler caused an exception while handling the removal of its thing", ex);
            }
        }
    });
}
 
Example #2
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void notifyBridgeAboutChildHandlerInitialization(final Thing thing) {
    final Bridge bridge = getBridge(thing.getBridgeUID());
    if (bridge != null) {
        ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BridgeHandler bridgeHandler = bridge.getHandler();
                    if (bridgeHandler != null) {
                        ThingHandler thingHandler = thing.getHandler();
                        if (thingHandler != null) {
                            bridgeHandler.childHandlerInitialized(thingHandler, thing);
                        }
                    }
                } catch (Exception e) {
                    logger.error(
                            "Exception occurred during bridge handler ('{}') notification about handler initialization of child '{}': {}",
                            bridge.getUID(), thing.getUID(), e.getMessage(), e);
                }
            }
        });
    }
}
 
Example #3
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void notifyThingsAboutBridgeStatusChange(final Bridge bridge, final ThingStatusInfo bridgeStatus) {
    if (ThingHandlerHelper.isHandlerInitialized(bridge)) {
        for (final Thing child : bridge.getThings()) {
            ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        ThingHandler handler = child.getHandler();
                        if (handler != null && ThingHandlerHelper.isHandlerInitialized(child)) {
                            handler.bridgeStatusChanged(bridgeStatus);
                        }
                    } catch (Exception e) {
                        logger.error(
                                "Exception occurred during notification about bridge status change on thing '{}': {}",
                                child.getUID(), e.getMessage(), e);
                    }
                }
            });
        }
    }
}
 
Example #4
Source File: WemoLightHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized WemoBridgeHandler getWemoBridgeHandler() {
    if (this.wemoBridgeHandler == null) {
        Bridge bridge = getBridge();
        if (bridge == null) {
            logger.error("Required bridge not defined for device {}.", wemoLightID);
            return null;
        }
        ThingHandler handler = bridge.getHandler();
        if (handler instanceof WemoBridgeHandler) {
            this.wemoBridgeHandler = (WemoBridgeHandler) handler;
        } else {
            logger.debug("No available bridge handler found for {} bridge {} .", wemoLightID, bridge.getUID());
            return null;
        }
    }
    return this.wemoBridgeHandler;
}
 
Example #5
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 #6
Source File: MqttBrokerHandlerFactory.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
    if (mqttService == null) {
        throw new IllegalStateException("MqttService must be bound, before ThingHandlers can be created");
    }
    if (!(thing instanceof Bridge)) {
        throw new IllegalStateException("A bridge type is expected");
    }
    final ThingTypeUID thingTypeUID = thing.getThingTypeUID();

    final AbstractBrokerHandler handler;
    if (thingTypeUID.equals(MqttBindingConstants.BRIDGE_TYPE_SYSTEMBROKER)) {
        handler = new SystemBrokerHandler((Bridge) thing, mqttService);
    } else if (thingTypeUID.equals(MqttBindingConstants.BRIDGE_TYPE_BROKER)) {
        handler = new BrokerHandler((Bridge) thing);
    } else {
        throw new IllegalStateException("Not supported " + thingTypeUID.toString());
    }
    createdHandler(handler);
    return handler;
}
 
Example #7
Source File: SonyAudioHandlerFactory.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();

    switch (thingTypeUID.getId()) {
        case SonyAudioBindingConstants.SONY_TYPE_STRDN1080:
            return new StrDn1080Handler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_HTCT800:
            return new HtCt800Handler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_HTST5000:
            return new HtSt5000Handler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_HTZ9F:
            return new HtZ9fHandler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_HTZF9:
            return new HtZf9Handler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_HTMT500:
            return new HtMt500Handler(thing, webSocketClient);
        case SonyAudioBindingConstants.SONY_TYPE_SRSZR5:
            return new SrsZr5Handler(thing, webSocketClient);
        default:
            return null;
    }
}
 
Example #8
Source File: TradfriHandlerFactory.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();

    if (GATEWAY_TYPE_UID.equals(thingTypeUID)) {
        TradfriGatewayHandler handler = new TradfriGatewayHandler((Bridge) thing);
        registerDiscoveryService(handler);
        return handler;
    } else if (THING_TYPE_DIMMER.equals(thingTypeUID) || THING_TYPE_REMOTE_CONTROL.equals(thingTypeUID)) {
        return new TradfriControllerHandler(thing);
    } else if (THING_TYPE_MOTION_SENSOR.equals(thingTypeUID)) {
        return new TradfriSensorHandler(thing);
    } else if (SUPPORTED_LIGHT_TYPES_UIDS.contains(thingTypeUID)) {
        return new TradfriLightHandler(thing);
    } else if (SUPPORTED_PLUG_TYPES_UIDS.contains(thingTypeUID)) {
        return new TradfriPlugHandler(thing);
    }
    return null;
}
 
Example #9
Source File: ThingLinkManager.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void informHandlerAboutLinkedChannel(Thing thing, Channel channel) {
    scheduler.submit(() -> {
        // Don't notify the thing if the thing isn't initialised
        if (ThingHandlerHelper.isHandlerInitialized(thing)) {
            ThingHandler handler = thing.getHandler();
            if (handler != null) {
                try {
                    handler.channelLinked(channel.getUID());
                } catch (Exception ex) {
                    logger.error("Exception occurred while informing handler: {}", ex.getMessage(), ex);
                }
            } else {
                logger.trace(
                        "Can not inform handler about linked channel, because no handler is assigned to the thing {}.",
                        thing.getUID());
            }
        }
    });
}
 
Example #10
Source File: ThingStatusInfoI18nLocalizationService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the translation of the description for the specified locale, using the translations from the bundles of
 * the given thingHandler and its parent classes. The description may contain arguments that may also need
 * translation (see class JavaDoc for an example); those arguments are translated in the same way.
 */
private String translateDescription(String description, Locale locale, ThingHandler thingHandler) {
    ParsedDescription parsedDescription = new ParsedDescription(description);

    Object[] translatedArgs = null;
    if (parsedDescription.args != null) {
        translatedArgs = Arrays.stream(parsedDescription.args).map(arg -> {
            if (I18nUtil.isConstant(arg)) {
                return getTranslationForClass(arg, locale, thingHandler.getClass());
            } else {
                return arg;
            }
        }).toArray(String[]::new);
    }

    return getTranslationForClass(parsedDescription.key, locale, thingHandler.getClass(), translatedArgs);
}
 
Example #11
Source File: ThingLinkManager.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void informHandlerAboutUnlinkedChannel(Thing thing, Channel channel) {
    scheduler.submit(() -> {
        // Don't notify the thing if the thing isn't initialised
        if (ThingHandlerHelper.isHandlerInitialized(thing)) {
            ThingHandler handler = thing.getHandler();
            if (handler != null) {
                try {
                    handler.channelUnlinked(channel.getUID());
                } catch (Exception ex) {
                    logger.error("Exception occurred while informing handler: {}", ex.getMessage(), ex);
                }
            } else {
                logger.trace(
                        "Can not inform handler about unlinked channel, because no handler is assigned to the thing {}.",
                        thing.getUID());
            }
        }
    });
}
 
Example #12
Source File: HomematicThingHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("null")
@Override
public synchronized void handleRemoval() {
    final Bridge bridge;
    final ThingHandler handler;

    if ((bridge = getBridge()) == null || (handler = bridge.getHandler()) == null) {
        super.handleRemoval();
        return;
    }

    final HomematicConfig config = bridge.getConfiguration().as(HomematicConfig.class);
    final boolean factoryResetOnDeletion = config.isFactoryResetOnDeletion();
    final boolean unpairOnDeletion = factoryResetOnDeletion || config.isUnpairOnDeletion();

    if (unpairOnDeletion) {
        deviceDeletionPending = true;
        ((HomematicBridgeHandler) handler).deleteFromGateway(UidUtils.getHomematicAddress(thing),
                factoryResetOnDeletion, false, true);
    } else {
        super.handleRemoval();
    }
}
 
Example #13
Source File: GenericWemoOSGiTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
protected Thing createThing(ThingTypeUID thingTypeUID, String channelID, String itemAcceptedType,
        WemoHttpCall wemoHttpCaller) {
    Configuration configuration = new Configuration();
    configuration.put(WemoBindingConstants.UDN, DEVICE_UDN);

    ThingUID thingUID = new ThingUID(thingTypeUID, TEST_THING_ID);

    ChannelUID channelUID = new ChannelUID(thingUID, channelID);
    Channel channel = ChannelBuilder.create(channelUID, itemAcceptedType).withType(DEFAULT_CHANNEL_TYPE_UID)
            .withKind(ChannelKind.STATE).withLabel("label").build();

    thing = ThingBuilder.create(thingTypeUID, thingUID).withConfiguration(configuration).withChannel(channel)
            .build();

    managedThingProvider.add(thing);

    ThingHandler handler = thing.getHandler();
    if (handler != null) {
        AbstractWemoHandler h = (AbstractWemoHandler) handler;
        h.setWemoHttpCaller(wemoHttpCaller);
    }

    return thing;
}
 
Example #14
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void notifyBridgeAboutChildHandlerDisposal(final Thing thing, final ThingHandler thingHandler) {
    final Bridge bridge = getBridge(thing.getBridgeUID());
    if (bridge != null) {
        ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BridgeHandler bridgeHandler = bridge.getHandler();
                    if (bridgeHandler != null) {
                        bridgeHandler.childHandlerDisposed(thingHandler, thing);
                    }
                } catch (Exception ex) {
                    logger.error(
                            "Exception occurred during bridge handler ('{}') notification about handler disposal of child '{}': {}",
                            bridge.getUID(), thing.getUID(), ex.getMessage(), ex);
                }
            }
        });
    }
}
 
Example #15
Source File: OpenWeatherMapHandlerFactory.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();

    if (THING_TYPE_WEATHER_API.equals(thingTypeUID)) {
        OpenWeatherMapAPIHandler handler = new OpenWeatherMapAPIHandler((Bridge) thing, httpClient, localeProvider);
        // register discovery service
        OpenWeatherMapDiscoveryService discoveryService = new OpenWeatherMapDiscoveryService(handler,
                locationProvider, localeProvider, i18nProvider);
        discoveryServiceRegs.put(handler.getThing().getUID(), bundleContext
                .registerService(DiscoveryService.class.getName(), discoveryService, new Hashtable<>()));
        return handler;
    } else if (THING_TYPE_WEATHER_AND_FORECAST.equals(thingTypeUID)) {
        return new OpenWeatherMapWeatherAndForecastHandler(thing);
    } else if (THING_TYPE_UVINDEX.equals(thingTypeUID)) {
        return new OpenWeatherMapUVIndexHandler(thing);
    }

    return null;
}
 
Example #16
Source File: HueLightHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
protected synchronized @Nullable HueClient getHueClient() {
    if (hueClient == null) {
        Bridge bridge = getBridge();
        if (bridge == null) {
            return null;
        }
        ThingHandler handler = bridge.getHandler();
        if (handler instanceof HueClient) {
            hueClient = (HueClient) handler;
            hueClient.registerLightStatusListener(this);
        } else {
            return null;
        }
    }
    return hueClient;
}
 
Example #17
Source File: AstroValidConfigurationTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void assertThingStatus(Configuration configuration, ThingStatus expectedStatus) {
    ThingUID thingUID = new ThingUID(THING_TYPE_SUN, TEST_SUN_THING_ID);

    Thing thing = mock(Thing.class);
    when(thing.getConfiguration()).thenReturn(configuration);
    when(thing.getUID()).thenReturn(thingUID);

    ThingHandlerCallback callback = mock(ThingHandlerCallback.class);
    CronScheduler cronScheduler = mock(CronScheduler.class);
    ThingHandler sunHandler = new SunHandler(thing, cronScheduler);
    sunHandler.setCallback(callback);

    sunHandler.initialize();

    ThingStatusInfo expectedThingStatus = new ThingStatusInfo(expectedStatus, ThingStatusDetail.NONE, null);
    verify(callback, times(1)).statusUpdated(thing, expectedThingStatus);
}
 
Example #18
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void thingRemoved(final Thing thing, ThingTrackerEvent thingTrackerEvent) {
    logger.debug("Thing '{}' is no longer tracked by ThingManager.", thing.getUID());

    ThingHandler thingHandler = thingHandlers.get(thing.getUID());
    if (thingHandler != null) {
        final ThingHandlerFactory thingHandlerFactory = findThingHandlerFactory(thing.getThingTypeUID());
        if (thingHandlerFactory != null) {
            unregisterAndDisposeHandler(thingHandlerFactory, thing, thingHandler);
            if (thingTrackerEvent == ThingTrackerEvent.THING_REMOVED) {
                safeCaller.create(thingHandlerFactory, ThingHandlerFactory.class).build()
                        .removeThing(thing.getUID());
            }
        } else {
            logger.warn("Cannot unregister handler. No handler factory for thing '{}' found.", thing.getUID());
        }
    }

    this.things.remove(thing);
}
 
Example #19
Source File: GenericWemoLightOSGiTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected Thing createThing(ThingTypeUID thingTypeUID, String channelID, String itemAcceptedType,
        WemoHttpCall wemoHttpCaller) {
    Configuration configuration = new Configuration();
    configuration.put(WemoBindingConstants.DEVICE_ID, WEMO_LIGHT_ID);

    ThingUID thingUID = new ThingUID(thingTypeUID, TEST_THING_ID);

    ChannelUID channelUID = new ChannelUID(thingUID, channelID);
    Channel channel = ChannelBuilder.create(channelUID, itemAcceptedType).withType(DEFAULT_CHANNEL_TYPE_UID)
            .withKind(ChannelKind.STATE).withLabel("label").build();
    ThingUID bridgeUID = new ThingUID(BRIDGE_TYPE_UID, WEMO_BRIDGE_ID);

    thing = ThingBuilder.create(thingTypeUID, thingUID).withConfiguration(configuration).withChannel(channel)
            .withBridge(bridgeUID).build();

    managedThingProvider.add(thing);

    ThingHandler handler = thing.getHandler();
    if (handler != null) {
        AbstractWemoHandler h = (AbstractWemoHandler) handler;
        h.setWemoHttpCaller(wemoHttpCaller);
    }

    return thing;
}
 
Example #20
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void doDisposeHandler(final ThingHandler thingHandler) {
    logger.debug("Calling dispose handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(), thingHandler);
    setThingStatus(thingHandler.getThing(), buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.NONE));
    safeCaller.create(thingHandler, ThingHandler.class).onTimeout(() -> {
        logger.warn("Disposing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(),
                SafeCaller.DEFAULT_TIMEOUT);
    }).onException(e -> {
        logger.error("Exception occurred while disposing handler of thing '{}': {}",
                thingHandler.getThing().getUID(), e.getMessage(), e);
    }).build().dispose();
}
 
Example #21
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void disposeHandler(Thing thing, ThingHandler thingHandler) {
    Lock lock = getLockForThing(thing.getUID());
    try {
        lock.lock();
        doDisposeHandler(thingHandler);
        if (hasBridge(thing)) {
            notifyBridgeAboutChildHandlerDisposal(thing, thingHandler);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #22
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 #23
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void doInitializeHandler(final ThingHandler thingHandler) {
    logger.debug("Calling initialize handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(),
            thingHandler);
    safeCaller.create(thingHandler, ThingHandler.class).onTimeout(() -> {
        logger.warn("Initializing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(),
                SafeCaller.DEFAULT_TIMEOUT);
    }).onException(e -> {
        ThingStatusInfo statusInfo = buildStatusInfo(ThingStatus.UNINITIALIZED,
                ThingStatusDetail.HANDLER_INITIALIZING_ERROR, e.getMessage());
        setThingStatus(thingHandler.getThing(), statusInfo);
        logger.error("Exception occurred while initializing handler of thing '{}': {}",
                thingHandler.getThing().getUID(), e.getMessage(), e);
    }).build().initialize();
}
 
Example #24
Source File: FSInternetRadioHandlerFactory.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();

    if (thingTypeUID.equals(THING_TYPE_RADIO)) {
        return new FSInternetRadioHandler(thing, httpClient);
    }

    return null;
}
 
Example #25
Source File: DmxTestHandlerFactory.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ThingHandler createHandler(Thing thing) {
    ThingTypeUID thingTypeUID = thing.getThingTypeUID();
    if (thingTypeUID.equals(TestBridgeHandler.THING_TYPE_TEST_BRIDGE)) {
        TestBridgeHandler handler = new TestBridgeHandler((Bridge) thing);
        return handler;
    }
    return null;
}
 
Example #26
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 #27
Source File: AbstractDmxThingTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertThingStatusWithoutBridge(ThingHandler handler) {
    handler.setCallback(mockCallback);
    handler.initialize();
    waitForAssert(() -> {
        assertEquals(ThingStatus.OFFLINE, handler.getThing().getStatus());
        assertEquals(ThingStatusDetail.CONFIGURATION_ERROR, handler.getThing().getStatusInfo().getStatusDetail());
    });
}
 
Example #28
Source File: DigitalSTROMHandlerFactory.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
    if (thingHandler instanceof BridgeHandler) {
        String uid = thingHandler.getThing().getUID().getAsString();
        if (discoveryServiceManagers.get(uid) != null) {
            discoveryServiceManagers.get(uid).unregisterDiscoveryServices(bundleContext);
            discoveryServiceManagers.remove(uid);
        }
    }
}
 
Example #29
Source File: WemoMakerHandlerOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertThatThingHandlesOnOffCommandCorrectly()
        throws MalformedURLException, URISyntaxException, ValidationException {
    Command command = OnOffType.OFF;

    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) {
        // Binary state 0 is equivalent to OFF
        if (result.contains("<BinaryState>0</BinaryState>")) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example #30
Source File: ThingManagerOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void thingManagerHandlesThingStatusUpdatesUninitializedAndInitializingCorrectly() {
    registerThingTypeProvider();

    ThingHandler thingHandler = mock(ThingHandler.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);

    registerService(thingHandlerFactory);

    final ThingStatusInfo uninitializedNone = ThingStatusInfoBuilder
            .create(ThingStatus.UNINITIALIZED, ThingStatusDetail.NONE).build();
    assertThat(thing.getStatusInfo(), is(uninitializedNone));

    managedThingProvider.add(thing);

    final ThingStatusInfo initializingNone = ThingStatusInfoBuilder
            .create(ThingStatus.INITIALIZING, ThingStatusDetail.NONE).build();
    waitForAssert(() -> assertThat(thing.getStatusInfo(), is(initializingNone)));

    unregisterService(thingHandlerFactory);

    final ThingStatusInfo uninitializedHandlerMissing = ThingStatusInfoBuilder
            .create(ThingStatus.UNINITIALIZED, ThingStatusDetail.HANDLER_MISSING_ERROR).build();
    waitForAssert(() -> assertThat(thing.getStatusInfo(), is(uninitializedHandlerMissing)));
}