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

The following examples show how to use org.eclipse.smarthome.core.thing.Thing#getUID() . 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: BaseThingHandlerFactory.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ThingHandler registerHandler(Thing thing) {
    ThingHandler thingHandler = createHandler(thing);
    if (thingHandler == null) {
        throw new IllegalStateException(this.getClass().getSimpleName()
                + " could not create a handler for the thing '" + thing.getUID() + "'.");
    }
    if ((thing instanceof Bridge) && !(thingHandler instanceof BridgeHandler)) {
        throw new IllegalStateException(
                "Created handler of bridge '" + thing.getUID() + "' must implement the BridgeHandler interface.");
    }
    setHandlerContext(thingHandler);
    registerConfigStatusProvider(thing, thingHandler);
    registerFirmwareUpdateHandler(thing, thingHandler);
    registerServices(thing, thingHandler);
    return thingHandler;
}
 
Example 2
Source File: PersistentInbox.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void addThingSafely(Thing thing) {
    ThingUID thingUID = thing.getUID();
    if (thingRegistry.get(thingUID) != null) {
        thingRegistry.remove(thingUID);
    }
    thingRegistry.add(thing);
}
 
Example 3
Source File: BaseThingHandlerFactory.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void unregisterServices(Thing thing) {
    ThingUID thingUID = thing.getUID();

    Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.remove(thingUID);
    if (serviceRegs != null) {
        for (ServiceRegistration<?> serviceReg : serviceRegs) {
            ThingHandlerService service = (ThingHandlerService) getBundleContext()
                    .getService(serviceReg.getReference());
            serviceReg.unregister();
            if (service != null) {
                service.deactivate();
            }
        }
    }
}
 
Example 4
Source File: ThingResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{thingUID}/firmware/{firmwareVersion}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update thing firmware.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 400, message = "Firmware update preconditions not satisfied."),
        @ApiResponse(code = 404, message = "Thing not found.") })
public Response updateFirmware(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
        @PathParam("thingUID") @ApiParam(value = "thing") String thingUID,
        @PathParam("firmwareVersion") @ApiParam(value = "version") String firmwareVersion) throws IOException {
    Thing thing = thingRegistry.get(new ThingUID(thingUID));
    if (thing == null) {
        logger.info("Received HTTP PUT request for firmware update at '{}' for the unknown thing '{}'.",
                uriInfo.getPath(), thingUID);
        return getThingNotFoundResponse(thingUID);
    }

    if (StringUtils.isEmpty(firmwareVersion)) {
        logger.info(
                "Received HTTP PUT request for firmware update at '{}' for thing '{}' with unknown firmware version '{}'.",
                uriInfo.getPath(), thingUID, firmwareVersion);
        return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Firmware version is empty");
    }

    ThingUID uid = thing.getUID();
    try {
        firmwareUpdateService.updateFirmware(uid, firmwareVersion, localeService.getLocale(language));
    } catch (IllegalArgumentException | IllegalStateException ex) {
        return JSONResponse.createResponse(Status.BAD_REQUEST, null,
                "Firmware update preconditions not satisfied.");
    }

    return Response.status(Status.OK).build();
}
 
Example 5
Source File: WemoHandlerOSGiTest.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(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) {
        // Binary state 0 is equivalent to OFF
        if (result.contains("<BinaryState>0</BinaryState>")) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example 6
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 7
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 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: BaseThingHandlerFactory.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private void registerServices(Thing thing, ThingHandler thingHandler) {
    ThingUID thingUID = thing.getUID();
    for (Class c : thingHandler.getServices()) {
        Object serviceInstance;
        try {
            serviceInstance = c.newInstance();

            ThingHandlerService ths = null;
            if (serviceInstance instanceof ThingHandlerService) {
                ths = (ThingHandlerService) serviceInstance;
                ths.setThingHandler(thingHandler);
            } else {
                logger.warn(
                        "Should register service={} for thingUID={}, but it does not implement the interface ThingHandlerService.",
                        c.getCanonicalName(), thingUID);
                continue;
            }

            Class[] interfaces = c.getInterfaces();
            LinkedList<String> serviceNames = new LinkedList<>();
            if (interfaces != null) {
                for (Class i : interfaces) {
                    String className = i.getCanonicalName();
                    // we only add specific ThingHandlerServices, i.e. those that derive from the
                    // ThingHandlerService interface, NOT the ThingHandlerService itself. We do this to register
                    // them as specific OSGi services later, rather than as a generic ThingHandlerService.
                    if (!ThingHandlerService.class.getCanonicalName().equals(className)) {
                        serviceNames.add(className);
                    }
                }
            }
            if (serviceNames.size() > 0) {
                String[] serviceNamesArray = serviceNames.toArray(new String[serviceNames.size()]);

                ServiceRegistration<?> serviceReg = this.bundleContext.registerService(serviceNamesArray,
                        serviceInstance, null);

                if (serviceReg != null) {
                    Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.get(thingUID);
                    if (serviceRegs == null) {
                        HashSet<ServiceRegistration<?>> set = new HashSet<>();
                        set.add(serviceReg);
                        this.thingHandlerServices.put(thingUID, set);
                    } else {
                        serviceRegs.add(serviceReg);
                    }
                    ths.activate();
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            logger.warn("Could not register service for class={}", c, e);
        }
    }
}
 
Example 10
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) {
    ThingUID thingUID = thing.getUID();
    if (thingUpdatedLock.contains(thingUID)) {
        // called from the thing handler itself, therefore
        // it exists, is initializing/initialized and
        // must not be informed (in order to prevent infinite loops)
        replaceThing(getThing(thingUID), thing);
    } else {
        Lock lock1 = getLockForThing(thing.getUID());
        try {
            lock1.lock();
            Thing oldThing = getThing(thingUID);
            ThingHandler thingHandler = replaceThing(oldThing, thing);
            if (thingHandler != null) {
                if (ThingHandlerHelper.isHandlerInitialized(thing) || isInitializing(thing)) {
                    if (oldThing != null) {
                        oldThing.setHandler(null);
                    }
                    thing.setHandler(thingHandler);
                    safeCaller.create(thingHandler, ThingHandler.class).build().thingUpdated(thing);
                } else {
                    logger.debug(
                            "Cannot notify handler about updated thing '{}', because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE).",
                            thing.getThingTypeUID());
                    if (thingHandler.getThing() == thing) {
                        logger.debug("Initializing handler of thing '{}'", thing.getThingTypeUID());
                        if (oldThing != null) {
                            oldThing.setHandler(null);
                        }
                        thing.setHandler(thingHandler);
                        initializeHandler(thing);
                    } else {
                        logger.debug("Replacing uninitialized handler for updated thing '{}'",
                                thing.getThingTypeUID());
                        ThingHandlerFactory thingHandlerFactory = getThingHandlerFactory(thing);
                        unregisterHandler(thingHandler.getThing(), thingHandlerFactory);
                        registerAndInitializeHandler(thing, thingHandlerFactory);
                    }
                }
            } else {
                registerAndInitializeHandler(thing, getThingHandlerFactory(thing));
            }
        } finally {
            lock1.unlock();
        }
    }
}
 
Example 11
Source File: DigitalIoConfig.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
public DigitalIoConfig(Thing thing, Integer channelIndex, OwDeviceParameterMap inParam, OwDeviceParameterMap outParam) {
    this.channelUID = new ChannelUID(thing.getUID(), String.format("%s%d", CHANNEL_DIGITAL, channelIndex));
    this.channelID = String.format("%s%d", CHANNEL_DIGITAL, channelIndex);
    this.inParam = inParam;
    this.outParam = outParam;
}
 
Example 12
Source File: HomeAssistantThingHandler.java    From smarthome with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Create a new thing handler for HomeAssistant MQTT components.
 * A channel type provider and a topic value receive timeout must be provided.
 *
 * @param thing The thing of this handler
 * @param channelTypeProvider A channel type provider
 * @param subscribeTimeout Timeout for the entire tree parsing and subscription. In milliseconds.
 * @param attributeReceiveTimeout The timeout per attribute field subscription. In milliseconds.
 */
public HomeAssistantThingHandler(Thing thing, MqttChannelTypeProvider channelTypeProvider, int subscribeTimeout,
        int attributeReceiveTimeout) {
    super(thing, subscribeTimeout);
    this.channelTypeProvider = channelTypeProvider;
    this.attributeReceiveTimeout = attributeReceiveTimeout;
    this.delayedProcessing = new DelayedBatchProcessing<>(attributeReceiveTimeout, this, scheduler);
    this.discoverComponents = new DiscoverComponents(thing.getUID(), scheduler, this, gson);
}