org.eclipse.smarthome.core.thing.ThingStatus Java Examples

The following examples show how to use org.eclipse.smarthome.core.thing.ThingStatus. 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: LIRCRemoteHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void initialize() {
    logger.debug("Initializing thing {}", getThing().getUID());
    config = getConfigAs(LIRCRemoteConfiguration.class);
    remoteName = config.getRemote();
    if (remoteName == null) {
        logger.error("Remote name is not set in {}", getThing().getUID());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remote name is not set");
    } else {
        bridgeHandler = (LIRCBridgeHandler) getBridge().getHandler();
        bridgeHandler.registerMessageListener(this);
        if (getBridge().getStatus() == ThingStatus.ONLINE) {
            updateStatus(ThingStatus.ONLINE);
        } else {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
        }
    }
}
 
Example #2
Source File: HueBridgeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method is called whenever the connection to the {@link HueBridge} is resumed.
 *
 * @throws ApiException if the physical device does not support this API call
 * @throws IOException if the physical device could not be reached
 */
private void onConnectionResumed() throws IOException, ApiException {
    logger.debug("Bridge connection resumed. Updating thing status to ONLINE.");

    if (!propertiesInitializedSuccessfully) {
        FullConfig fullConfig = hueBridge.getFullConfig();
        Config config = fullConfig.getConfig();
        if (config != null) {
            Map<String, String> properties = editProperties();
            properties.put(PROPERTY_SERIAL_NUMBER, config.getMACAddress().replaceAll(":", "").toLowerCase());
            properties.put(PROPERTY_FIRMWARE_VERSION, config.getSoftwareVersion());
            updateProperties(properties);
            propertiesInitializedSuccessfully = true;
        }
    }

    updateStatus(ThingStatus.ONLINE);
}
 
Example #3
Source File: MagicFirmwareUpdateThingHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void updateFirmware(Firmware firmware, ProgressCallback progressCallback) {
    progressCallback.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING, ProgressStep.UPDATING,
            ProgressStep.REBOOTING, ProgressStep.WAITING);

    updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.FIRMWARE_UPDATING, "Firmware is updating");

    progressCallback.next();
    for (int percent = 1; percent < 100; percent++) {
        try {
            Thread.sleep(STEP_DELAY);
        } catch (InterruptedException e) {
            progressCallback.failed("Magic firmware update progress callback interrupted while sleeping", e);
        }
        progressCallback.update(percent);
        if (percent % 20 == 0) {
            progressCallback.next();
        }
    }

    getThing().setProperty(Thing.PROPERTY_FIRMWARE_VERSION, firmware.getVersion());

    progressCallback.success();

    updateStatus(ThingStatus.ONLINE);
}
 
Example #4
Source File: TradfriGatewayHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void establishConnection() {
    TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);

    this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
    this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/"
            + GATEWAY_DETAILS;
    try {
        URI uri = new URI(gatewayURI);
        deviceClient = new TradfriCoapClient(uri);
    } catch (URISyntaxException e) {
        logger.error("Illegal gateway URI '{}': {}", gatewayURI, e.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        return;
    }

    DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
    builder.setPskStore(new StaticPskStore(configuration.identity, configuration.preSharedKey.getBytes()));
    dtlsConnector = new DTLSConnector(builder.build(), new InMemoryConnectionStore(100, 60));
    endPoint = new TradfriCoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
    deviceClient.setEndpoint(endPoint);
    updateStatus(ThingStatus.UNKNOWN);

    // schedule a new scan every minute
    scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
}
 
Example #5
Source File: ThingStatusInfoI18nLocalizationServiceOSGiTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void thingStatusInfoLocalizedForOfflineStatusWithTwoArguments() {
    setThingStatusInfo(thing, new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "@text/offline.with-two-params [\"@text/communication-problems\", \"120\"]"));

    ThingStatusInfo thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing,
            null);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing is offline because of communication problems. Pls try again after 120 seconds.")));

    thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing, Locale.GERMAN);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing ist wegen Kommunikationsprobleme offline. Bitte versuchen Sie es in 120 Sekunden erneut.")));

    thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing, Locale.ENGLISH);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing is offline because of communication problems. Pls try again after 120 seconds.")));
}
 
Example #6
Source File: HeosGroupHandler.java    From org.openhab.binding.heos with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("null")
@Override
public void run() {
    initChannelHandlerFatory();
    heosGroup = heos.getGroupState(heosGroup);
    if (!heosGroup.isOnline() || !heosGroup.getGroupMemberHash()
            .equals(thing.getConfiguration().get(GROUP_MEMBER_HASH).toString())) {
        bridge.setThingStatusOffline(thing.getUID());
        setStatusOffline();
        return;
    }
    updateStatus(ThingStatus.ONLINE);
    bridge.setThingStatusOnline(thing.getUID()); // informs the System about the existing group
    HashMap<String, HeosGroup> usedToFillOldGroupMap = new HashMap<>();
    usedToFillOldGroupMap.put(heosGroup.getNameHash(), heosGroup);
    heos.addHeosGroupToOldGroupMap(usedToFillOldGroupMap);
    id = heosGroup.getGid(); // Updates the id of the group. Needed if group leader has changed
    refreshChannels();
}
 
Example #7
Source File: MeteoBlueBridgeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Initialize the bridge.
 */
@Override
public void initialize() {
    logger.debug("Initializing meteoblue bridge");

    MeteoBlueBridgeConfig config = getConfigAs(MeteoBlueBridgeConfig.class);
    String apiKeyTemp = config.getApiKey();
    if (StringUtils.isBlank(apiKeyTemp)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                "Cannot initialize meteoblue bridge. No apiKey provided.");
        return;
    }

    apiKey = apiKeyTemp;

    healthCheck();
}
 
Example #8
Source File: TradfriGatewayHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onUpdate(JsonElement data) {
    logger.debug("onUpdate response: {}", data);

    if (endPoint != null) {
        try {
            JsonArray array = data.getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                requestDeviceDetails(array.get(i).getAsString());
            }
        } catch (JsonSyntaxException e) {
            logger.debug("JSON error: {}", e.getMessage());
            setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
        }
    }
}
 
Example #9
Source File: HomematicBridgeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onDutyCycleRatioUpdate(int dutyCycleRatio) {
    synchronized (dutyCycleRatioUpdateLock) {
        this.dutyCycleRatio = dutyCycleRatio;
        Channel dutyCycleRatioChannel = thing.getChannel(CHANNEL_TYPE_DUTY_CYCLE_RATIO);
        if (dutyCycleRatioChannel != null) {
            this.updateState(dutyCycleRatioChannel.getUID(), new DecimalType(dutyCycleRatio));
        }

        if (!isInDutyCycle && dutyCycleRatio >= DUTY_CYCLE_RATIO_LIMIT) {
            logger.info("Duty cycle threshold exceeded by homematic bridge {}, it will go OFFLINE.",
                    thing.getUID());
            isInDutyCycle = true;
            this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DUTY_CYCLE);
        } else if (isInDutyCycle && dutyCycleRatio < DUTY_CYCLE_RATIO_LIMIT) {
            logger.info("Homematic bridge {} fell below duty cycle threshold and will come ONLINE again.",
                    thing.getUID());
            isInDutyCycle = false;
            this.updateStatus(ThingStatus.ONLINE);
        }
    }
}
 
Example #10
Source File: IpCameraGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void initialize() {
    config = thing.getConfiguration();
    serverPort = Integer.parseInt(config.get(CONFIG_SERVER_PORT).toString());
    pollTimeInSeconds = new BigDecimal(config.get(CONFIG_POLL_CAMERA_MS).toString());
    motionChangesOrder = (boolean) config.get(CONFIG_MOTION_CHANGES_ORDER);
    pollTimeInSeconds = pollTimeInSeconds.divide(new BigDecimal(1000), 1, RoundingMode.HALF_UP);
    if (serverPort == -1) {
        logger.warn("The SERVER_PORT = -1 which disables a lot of features. See readme for more info.");
    } else if (serverPort < 1025) {
        logger.warn("The SERVER_PORT is <= 1024 and may cause permission errors under Linux, try a higher port.");
    }
    if (!"-1".contentEquals(config.get(CONFIG_SERVER_PORT).toString())) {
        startStreamServer(true);
    } else {
        logger.warn("SERVER_PORT is -1 which disables all serving features of the camera group.");
    }
    updateStatus(ThingStatus.ONLINE);
    pollCameraGroupJob = pollCameraGroup.scheduleAtFixedRate(pollingCameraGroup, 10000,
            Integer.parseInt(config.get(CONFIG_POLL_CAMERA_MS).toString()), TimeUnit.MILLISECONDS);
}
 
Example #11
Source File: ThingManagerOSGiJavaTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void assertThingStatus(Map<String, Object> propsThing, Map<String, Object> propsChannel, ThingStatus status,
        ThingStatusDetail statusDetail) {
    Configuration configThing = new Configuration(propsThing);
    Configuration configChannel = new Configuration(propsChannel);

    Thing thing = ThingBuilder.create(THING_TYPE_UID, THING_UID).withChannels(Collections.singletonList( //
            ChannelBuilder.create(CHANNEL_UID, "Switch").withType(CHANNEL_TYPE_UID).withConfiguration(configChannel)
                    .build() //
    )).withConfiguration(configThing).build();

    managedThingProvider.add(thing);

    waitForAssert(() -> {
        assertEquals(status, thing.getStatus());
        assertEquals(statusDetail, thing.getStatusInfo().getStatusDetail());
    });

    managedThingProvider.remove(thing.getUID());
}
 
Example #12
Source File: ThingStatusInfoI18nLocalizationServiceOSGiTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void thingStatusInfoLocalizedForMalformedArguments() {
    setThingStatusInfo(thing, new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "@text/offline.with-two-params   [   \"@text/communication-problems\", ,      \"120\"  ]"));

    ThingStatusInfo thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing,
            null);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing is offline because of communication problems. Pls try again after 120 seconds.")));

    thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing, Locale.GERMAN);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing ist wegen Kommunikationsprobleme offline. Bitte versuchen Sie es in 120 Sekunden erneut.")));

    thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing, Locale.ENGLISH);
    assertThat(thingStatusInfo, is(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
            "Thing is offline because of communication problems. Pls try again after 120 seconds.")));
}
 
Example #13
Source File: BoseSoundTouchHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onWebSocketError(Throwable e) {
    logger.debug("{}: Error during websocket communication: {}", getDeviceName(), e.getMessage(), e);
    updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
    if (commandExecutor != null) {
        commandExecutor.postOperationMode(OperationModeType.OFFLINE);
        commandExecutor = null;
    }
    if (session != null) {
        session.close(StatusCode.SERVER_ERROR, getDeviceName() + ": Failure: " + e.getMessage());
        session = null;
    }
}
 
Example #14
Source File: DeviceHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
    if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
        if (dSID != null) {
            if (getDssBridgeHandler() != null) {
                if (device == null) {
                    updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
                            "waiting for listener registration");
                    dssBridgeHandler.registerDeviceStatusListener(this);
                } else {
                    updateStatus(ThingStatus.ONLINE);
                }
            } else {
                updateStatus(ThingStatus.OFFLINE);
            }
        } else {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No dSID is set!");
        }
    }
    if (bridgeStatusInfo.getStatus().equals(ThingStatus.OFFLINE)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
    }
    if (bridgeStatusInfo.getStatus().equals(ThingStatus.REMOVED)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Bridge has been removed.");
    }
    logger.debug("Set status to {}", getThing().getStatusInfo());
}
 
Example #15
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 #16
Source File: MultisensorThingHandlerTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefresh() throws OwException {
    thingHandler.initialize();

    // needed to determine initialization is finished
    waitForAssert(() -> assertEquals(ThingStatus.UNKNOWN, thingHandler.getThing().getStatusInfo().getStatus()));

    thingHandler.refresh(bridgeHandler, System.currentTimeMillis());

    inOrder.verify(bridgeHandler, times(1)).checkPresence(new SensorId(TEST_ID));
    inOrder.verify(bridgeHandler, times(3)).readDecimalType(eq(new SensorId(TEST_ID)), any());

    inOrder.verifyNoMoreInteractions();
}
 
Example #17
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void updateChildThingStatusForDisabledBridges(Bridge bridge) {
    for (Thing childThing : bridge.getThings()) {
        ThingStatusDetail statusDetail = childThing.getStatusInfo().getStatusDetail();
        if (childThing.getStatus() == ThingStatus.UNINITIALIZED && statusDetail != ThingStatusDetail.DISABLED) {
            setThingStatus(childThing,
                    buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.BRIDGE_UNINITIALIZED));
        }
    }
}
 
Example #18
Source File: ChangeThingTypeOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void initialize() {
    updateStatus(ThingStatus.ONLINE);
    genericInits++;
    if (selfChanging) {
        Map<String, Object> properties = new HashMap<>(1);
        properties.put("providedspecific", "there");
        changeThingType(THING_TYPE_SPECIFIC_UID, new Configuration(properties));
    }
}
 
Example #19
Source File: ChangeThingTypeOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertChangingTheThingTypeWorks() {
    // println "[ChangeThingTypeOSGiTest] ======== assert changing the ThingType works"
    Thing thing = ThingFactory.createThing(thingTypeGeneric, new ThingUID("testBinding", "testThing"),
            new Configuration(), null, configDescriptionRegistry);
    thing.setProperty("universal", "survives");
    managedThingProvider.add(thing);

    // Pre-flight checks - see below
    assertThat(thing.getHandler(), instanceOf(GenericThingHandler.class));
    assertThat(thing.getConfiguration().get("parametergeneric"), is("defaultgeneric"));
    assertThat(thing.getConfiguration().get("providedspecific"), is(nullValue()));
    assertThat(thing.getChannels().size(), is(1));
    assertThat(thing.getChannels().get(0).getUID(), is(CHANNEL_GENERIC_UID));
    assertThat(thing.getProperties().get("universal"), is("survives"));

    ThingHandlerFactory handlerFactory = getService(ThingHandlerFactory.class, SampleThingHandlerFactory.class);
    assertThat(handlerFactory, not(nullValue()));

    thing.getHandler().handleCommand(mock(ChannelUID.class), mock(Command.class));
    waitForAssert(() -> {
        assertThat(thing.getStatus(), is(ThingStatus.ONLINE));
    }, 4000, 100);

    // Now do the actual migration
    Map<String, Object> properties = new HashMap<>(1);
    properties.put("providedspecific", "there");
    ((BaseThingHandler) thing.getHandler()).changeThingType(THING_TYPE_SPECIFIC_UID, new Configuration(properties));

    assertThingWasChanged(thing);
}
 
Example #20
Source File: ChannelStateDescriptionProviderOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ThingHandler createHandler(Thing thing) {
    return new BaseThingHandler(thing) {
        @Override
        public void handleCommand(ChannelUID channelUID, Command command) {
        }

        @Override
        public void initialize() {
            updateStatus(ThingStatus.ONLINE);
        }
    };
}
 
Example #21
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void statusUpdated(Thing thing, ThingStatusInfo statusInfo) {
    // note: all provoked operations based on a status update should be executed asynchronously!
    ThingStatusInfo oldStatusInfo = thing.getStatusInfo();
    ensureValidStatus(oldStatusInfo.getStatus(), statusInfo.getStatus());

    if (ThingStatus.REMOVING.equals(oldStatusInfo.getStatus())
            && !ThingStatus.REMOVED.equals(statusInfo.getStatus())) {
        // only allow REMOVING -> REMOVED transition, all others are illegal
        throw new IllegalArgumentException(MessageFormat.format(
                "Illegal status transition from REMOVING to {0}, only REMOVED would have been allowed.",
                statusInfo.getStatus()));
    }

    // update thing status and send event about new status
    setThingStatus(thing, statusInfo);

    // if thing is a bridge
    if (isBridge(thing)) {
        handleBridgeStatusUpdate((Bridge) thing, statusInfo, oldStatusInfo);
    }
    // if thing has a bridge
    if (hasBridge(thing)) {
        handleBridgeChildStatusUpdate(thing, oldStatusInfo);
    }
    // notify thing registry about thing removal
    if (ThingStatus.REMOVED.equals(thing.getStatus())) {
        notifyRegistryAboutForceRemove(thing);
    }
}
 
Example #22
Source File: DeviceHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleRemoval() {
    if (getDssBridgeHandler() != null) {
        this.dssBridgeHandler.childThingRemoved(dSID);
    }
    updateStatus(ThingStatus.REMOVED);
}
 
Example #23
Source File: HomematicThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates the state of the given channel.
 */
protected void handleRefresh(ChannelUID channelUID) {
    try {
        if (thing.getStatus() == ThingStatus.ONLINE) {
            logger.debug("Updating channel '{}' from thing id '{}'", channelUID, getThing().getUID().getId());
            updateChannelState(channelUID);
        }
    } catch (Exception ex) {
        logger.warn("{}", ex.getMessage());
    }
}
 
Example #24
Source File: TradfriThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) {
    if (active && getBridge().getStatus() != ThingStatus.OFFLINE && status != ThingStatus.ONLINE) {
        updateStatus(status, statusDetail);
        // we are offline and lost our observe relation - let's try to establish the connection in 10 seconds again
        scheduler.schedule(() -> {
            if (observeRelation != null) {
                observeRelation.reactiveCancel();
                observeRelation = null;
            }
            observeRelation = coapClient.startObserve(this);
        }, 10, TimeUnit.SECONDS);
    }
}
 
Example #25
Source File: MagicDelayedOnlineHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (channelUID.getId().equals("number")) {
        if (command instanceof DecimalType) {
            DecimalType cmd = (DecimalType) command;
            int cmdInt = cmd.intValue();
            ThingStatus status = cmdInt > 0 ? ThingStatus.ONLINE : ThingStatus.OFFLINE;
            int waitTime = Math.abs(cmd.intValue());
            scheduler.schedule(() -> updateStatus(status), waitTime, TimeUnit.SECONDS);
        }
    }
}
 
Example #26
Source File: BeaconBluetoothHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void initialize() {
    try {
        address = new BluetoothAddress(getConfig().get(BluetoothBindingConstants.CONFIGURATION_ADDRESS).toString());
    } catch (IllegalArgumentException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getLocalizedMessage());
        return;
    }

    Bridge bridge = getBridge();
    if (bridge == null) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Not associated with any bridge");
        return;
    }

    BridgeHandler bridgeHandler = bridge.getHandler();
    if (!(bridgeHandler instanceof BluetoothAdapter)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                "Associated with an unsupported bridge");
        return;
    }

    adapter = (BluetoothAdapter) bridgeHandler;

    try {
        deviceLock.lock();
        device = adapter.getDevice(address);
        device.addListener(this);
    } finally {
        deviceLock.unlock();
    }

    updateStatus(ThingStatus.UNKNOWN);
}
 
Example #27
Source File: BaseThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates the status of the thing.
 *
 * @param status the status
 * @param statusDetail the detail of the status
 * @param description the description of the status
 */
protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
    synchronized (this) {
        if (this.callback != null) {
            ThingStatusInfoBuilder statusBuilder = ThingStatusInfoBuilder.create(status, statusDetail);
            ThingStatusInfo statusInfo = statusBuilder.withDescription(description).build();
            this.callback.statusUpdated(this.thing, statusInfo);
        } else {
            logger.warn("Handler {} tried updating the thing status although the handler was already disposed.",
                    this.getClass().getSimpleName());
        }
    }
}
 
Example #28
Source File: __bindingIdCamelCase__HandlerTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void initializeShouldCallTheCallback() {
    // mock getConfiguration to prevent NPEs
    when(thing.getConfiguration()).thenReturn(new Configuration());
    
    // we expect the handler#initialize method to call the callback during execution and
    // pass it the thing and a ThingStatusInfo object containing the ThingStatus of the thing.
    handler.initialize();

    // the argument captor will capture the argument of type ThingStatusInfo given to the
    // callback#statusUpdated method.
    ArgumentCaptor<ThingStatusInfo> statusInfoCaptor = ArgumentCaptor.forClass(ThingStatusInfo.class);

    // verify the interaction with the callback and capture the ThingStatusInfo argument:
    waitForAssert(() -> {
        verify(callback, times(2)).statusUpdated(eq(thing), statusInfoCaptor.capture());
    });
    
    // assert that the (temporary) UNKNOWN status was given first:
    assertThat(statusInfoCaptor.getAllValues().get(0).getStatus(), is(ThingStatus.UNKNOWN));
    
    
    // assert that ONLINE status was given later:
    assertThat(statusInfoCaptor.getAllValues().get(1).getStatus(), is(ThingStatus.ONLINE));

    
    // See the documentation at 
    // https://www.eclipse.org/smarthome/documentation/development/testing.html#assertions 
    // to see when to use Hamcrest assertions (assertThat) or JUnit assertions. 
}
 
Example #29
Source File: BaseThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
    if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE
            && getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) {
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
    } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
    }
}
 
Example #30
Source File: WemoCoffeeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        if (!isUpnpDeviceRegistered()) {
            logger.debug("WeMo UPnP device {} not yet registered", getUDN());
        }

        updateWemoState();
        onSubscription();
    } catch (Exception e) {
        logger.debug("Exception during poll : {}", e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
    }
}