org.eclipse.smarthome.core.library.types.DecimalType Java Examples

The following examples show how to use org.eclipse.smarthome.core.library.types.DecimalType. 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: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verify the preset channel is updated.
 */
@Test
public void presetChannelUpdated() {
    String presetChannelID = FSInternetRadioBindingConstants.CHANNEL_PRESET;
    String acceptedItemType = acceptedItemTypes.get(presetChannelID);
    createChannel(DEFAULT_THING_UID, presetChannelID, acceptedItemType);

    Thing radioThing = initializeRadioThing(DEFAULT_COMPLETE_CONFIGURATION);
    testRadioThingConsideringConfiguration(radioThing);
    turnTheRadioOn(radioThing);

    ChannelUID presetChannelUID = getChannelUID(radioThing, FSInternetRadioBindingConstants.CHANNEL_PRESET);
    initializeItem(presetChannelUID, DEFAULT_TEST_ITEM_NAME, acceptedItemType);

    radioHandler.handleCommand(presetChannelUID, DecimalType.valueOf("100"));
    waitForAssert(() -> {
        assertTrue("We should be able to set value to the preset",
                radioServiceDummy.containsRequestParameter(100, PRESET));
        radioServiceDummy.clearRequestParameters();
    });
}
 
Example #2
Source File: CommunicationManagerTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testItemCommandEvent_Decimal2Quantity_2() {
    // Take unit from state description
    StateDescriptionService stateDescriptionService = mock(StateDescriptionService.class);
    when(stateDescriptionService.getStateDescription(ITEM_NAME_3, null)).thenReturn(
            StateDescriptionFragmentBuilder.create().withPattern("%.1f °F").build().toStateDescription());
    ITEM_3.setStateDescriptionService(stateDescriptionService);

    manager.receive(ItemEventFactory.createCommandEvent(ITEM_NAME_3, DecimalType.valueOf("20")));
    waitForAssert(() -> {
        verify(stateProfile).onCommandFromItem(eq(QuantityType.valueOf("20 °F")));
    });
    verifyNoMoreInteractions(stateProfile);
    verifyNoMoreInteractions(triggerProfile);

    ITEM_3.setStateDescriptionService(null);
}
 
Example #3
Source File: AbstractDigitalOwDevice.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public boolean writeChannel(OwBaseBridgeHandler bridgeHandler, Integer ioChannel, Command command) {
    if (ioChannel < getChannelCount()) {
        try {
            if (ioConfig.get(ioChannel).isOutput()) {
                DecimalType value = ((OnOffType) command).as(DecimalType.class);
                if (value == null) {
                    throw new OwException("command is null");
                }
                bridgeHandler.writeDecimalType(sensorId, ioConfig.get(ioChannel).getParameter(), value);
                return true;
            } else {
                return false;
            }
        } catch (OwException e) {
            logger.info("could not write {} to {}: {}", command, ioChannel, e.getMessage());
            return false;
        }
    } else {
        throw new IllegalArgumentException("channel number out of range");
    }
}
 
Example #4
Source File: CircuitHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onDeviceStateChanged(DeviceStateUpdate deviceStateUpdate) {
    if (deviceStateUpdate != null && DeviceStateUpdate.UPDATE_CIRCUIT_METER.equals(deviceStateUpdate.getType())) {
        if (deviceStateUpdate.getValue() instanceof CachedMeteringValue) {
            CachedMeteringValue cachedVal = (CachedMeteringValue) deviceStateUpdate.getValue();
            if (MeteringUnitsEnum.WH.equals(cachedVal.getMeteringUnit())) {
                if (cachedVal.getMeteringType().equals(MeteringTypeEnum.ENERGY)) {
                    updateState(getChannelID(cachedVal), new DecimalType(cachedVal.getValue() * 0.001));
                } else {
                    updateState(getChannelID(cachedVal), new DecimalType(cachedVal.getValue()));
                }
            }
        }
    }

}
 
Example #5
Source File: ValueTests.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void percentCalc() {
    PercentageValue v = new PercentageValue(new BigDecimal(10.0), new BigDecimal(110.0), new BigDecimal(1.0), null,
            null);
    v.update(new DecimalType(110.0));
    assertThat((PercentType) v.getChannelState(), is(new PercentType(100)));
    assertThat(v.getMQTTpublishValue(), is("110"));
    v.update(new DecimalType(10.0));
    assertThat((PercentType) v.getChannelState(), is(new PercentType(0)));
    assertThat(v.getMQTTpublishValue(), is("10"));

    v.update(OnOffType.ON);
    assertThat((PercentType) v.getChannelState(), is(new PercentType(100)));
    v.update(OnOffType.OFF);
    assertThat((PercentType) v.getChannelState(), is(new PercentType(0)));
}
 
Example #6
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 #7
Source File: SitemapResourceTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void whenLongPolling_ShouldObserveItemsFromVisibilityRules() {
    new Thread(() -> {
        try {
            Thread.sleep(STATE_UPDATE_WAIT_TIME); // wait for the #getPageData call and listeners to attach to the
                                                  // item
            visibilityRuleItem.setState(new DecimalType(BigDecimal.ONE));
        } catch (InterruptedException e) {
        }
    }).start();

    // non-null is sufficient here.
    when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(Collections.emptyList());

    Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null);

    PageDTO pageDTO = (PageDTO) response.getEntity();
    assertThat(pageDTO.timeout, is(false)); // assert that the item state change did trigger the blocking method to
                                            // return
}
 
Example #8
Source File: EDS006xTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void lightChannel() {
    instantiateDevice();

    try {
        Mockito.when(mockBridgeHandler.checkPresence(testSensorId)).thenReturn(OnOffType.ON);
        Mockito.when(mockBridgeHandler.readDecimalType(eq(testSensorId), any())).thenReturn(new DecimalType(100));

        testDevice.enableChannel(CHANNEL_LIGHT);
        ((EDS006x) testDevice).configureChannels(OwSensorType.EDS0068);
        testDevice.refresh(mockBridgeHandler, true);

        inOrder.verify(mockBridgeHandler).readDecimalType(eq(testSensorId), any());
        inOrder.verify(mockThingHandler).postUpdate(eq(CHANNEL_LIGHT), eq(new QuantityType<>("100 lx")));

        inOrder.verifyNoMoreInteractions();
    } catch (OwException e) {
        Assert.fail("caught unexpected OwException");
    }
}
 
Example #9
Source File: GroupItemTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void assertCyclicGroupItemsCalculateStateWithSubGroupFunction() {
    GroupFunction countFn = new ArithmeticGroupFunction.Count(new StringType(".*"));
    GroupItem rootGroup = new GroupItem("rootGroup", new SwitchItem("baseItem"), countFn);
    TestItem rootMember = new TestItem("rootMember");
    rootGroup.addMember(rootMember);

    GroupItem group1 = new GroupItem("group1");
    GroupItem group2 = new GroupItem("group2", new SwitchItem("baseItem"), new ArithmeticGroupFunction.Sum());

    rootGroup.addMember(group1);
    group1.addMember(group2);
    group2.addMember(group1);

    group1.addMember(new TestItem("sub1"));
    group2.addMember(new TestItem("sub2-1"));
    group2.addMember(new TestItem("sub2-2"));
    group2.addMember(new TestItem("sub2-3"));

    // count: rootMember, sub1, group2
    assertThat(rootGroup.getStateAs(DecimalType.class), is(new DecimalType(3)));
}
 
Example #10
Source File: GroupItemTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void assertCyclicGroupItemsCalculateState() {
    GroupFunction countFn = new ArithmeticGroupFunction.Count(new StringType(".*"));
    GroupItem rootGroup = new GroupItem("rootGroup", new SwitchItem("baseItem"), countFn);
    TestItem rootMember = new TestItem("rootMember");
    rootGroup.addMember(rootMember);

    GroupItem group1 = new GroupItem("group1");
    GroupItem group2 = new GroupItem("group2");

    rootGroup.addMember(group1);
    group1.addMember(group2);
    group2.addMember(group1);

    group1.addMember(new TestItem("sub1"));
    group2.addMember(new TestItem("sub2-1"));
    group2.addMember(new TestItem("sub2-2"));
    group2.addMember(new TestItem("sub2-3"));

    // count: rootMember, sub1, sub2-1, sub2-2, sub2-3
    assertThat(rootGroup.getStateAs(DecimalType.class), is(new DecimalType(5)));
}
 
Example #11
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Handle the execution of the notification sound by sequentially executing the required steps.
 *
 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
 */
private void handleNotificationSound(Command notificationURL, ZonePlayerHandler coordinator) {
    String originalVolume = (isAdHocGroup() || isStandalonePlayer()) ? getVolume() : coordinator.getVolume();
    coordinator.stop();
    coordinator.waitForNotTransportState(STATE_PLAYING);
    applyNotificationSoundVolume();
    long notificationPosition = coordinator.getQueueSize() + 1;
    coordinator.addURIToQueue(notificationURL.toString(), "", notificationPosition, false);
    coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
    coordinator.setPositionTrack(notificationPosition);
    coordinator.play();
    coordinator.waitForFinishedNotification();
    if (originalVolume != null) {
        setVolumeForGroup(DecimalType.valueOf(originalVolume));
    }
    coordinator.removeRangeOfTracksFromQueue(new StringType(Long.toString(notificationPosition) + ",1"));
}
 
Example #12
Source File: TradfriControllerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onUpdate(JsonElement data) {
    if (active && !(data.isJsonNull())) {
        state = new TradfriControllerData(data);
        updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE);

        DecimalType batteryLevel = state.getBatteryLevel();
        if (batteryLevel != null) {
            updateState(CHANNEL_BATTERY_LEVEL, batteryLevel);
        }

        OnOffType batteryLow = state.getBatteryLow();
        if (batteryLow != null) {
            updateState(CHANNEL_BATTERY_LOW, batteryLow);
        }

        updateDeviceProperties(state);

        logger.debug(
                "Updating thing for controllerId {} to state {batteryLevel: {}, batteryLow: {}, firmwareVersion: {}, modelId: {}, vendor: {}}",
                state.getDeviceId(), batteryLevel, batteryLow, state.getFirmwareVersion(), state.getModelId(),
                state.getVendor());
    }
}
 
Example #13
Source File: DS2438Test.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void noChannel() {
    instantiateDevice();

    try {
        Mockito.when(mockBridgeHandler.checkPresence(testSensorId)).thenReturn(OnOffType.ON);
        Mockito.when(mockBridgeHandler.readDecimalType(eq(testSensorId), any())).thenReturn(new DecimalType(2.0));

        testDevice.configureChannels();
        inOrder.verify(mockThingHandler).getThing();
        testDevice.refresh(mockBridgeHandler, true);

        inOrder.verifyNoMoreInteractions();
    } catch (OwException e) {
        Assert.fail("caught unexpected OwException");
    }
}
 
Example #14
Source File: LightStateConverter.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private static HSBType fromHSBtoHSBType(State lightState) {
    int hue = (int) Math.round(lightState.getHue() / HUE_FACTOR) % 360;

    int saturationInPercent = (int) Math.ceil(lightState.getSaturation() / SATURATION_FACTOR);
    saturationInPercent = restrictToBounds(saturationInPercent);

    int brightnessInPercent = (int) Math.ceil(lightState.getBrightness() / BRIGHTNESS_FACTOR);
    brightnessInPercent = restrictToBounds(brightnessInPercent);

    return new HSBType(new DecimalType(hue), new PercentType(saturationInPercent),
            new PercentType(brightnessInPercent));
}
 
Example #15
Source File: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void testChannelWithINCREASEAndDECREASECommands(ChannelUID channelUID, Item item) {
    synchronized (channelUID) {
        // First we have to make sure that the item state is 0
        radioHandler.handleCommand(channelUID, DecimalType.valueOf("0"));
        waitForAssert(() -> {
            assertTrue("We should be able to turn on the radio",
                    radioServiceDummy.containsRequestParameter(1, CHANNEL_POWER));
            radioServiceDummy.clearRequestParameters();
        });

        radioHandler.handleCommand(channelUID, IncreaseDecreaseType.INCREASE);

        waitForAssert(() -> {
            assertTrue("We should be able to increase the volume correctly",
                    radioServiceDummy.containsRequestParameter(1, VOLUME));
            radioServiceDummy.clearRequestParameters();
        });

        radioHandler.handleCommand(channelUID, IncreaseDecreaseType.DECREASE);
        waitForAssert(() -> {
            assertTrue("We should be able to increase the volume correctly",
                    radioServiceDummy.containsRequestParameter(0, VOLUME));
            radioServiceDummy.clearRequestParameters();
        });

        // Trying to decrease one more time
        radioHandler.handleCommand(channelUID, IncreaseDecreaseType.DECREASE);
        waitForAssert(() -> {
            assertFalse("We should be able to decrease the volume correctly",
                    radioServiceDummy.containsRequestParameter(0, VOLUME));
            radioServiceDummy.clearRequestParameters();
        });
    }
}
 
Example #16
Source File: BeaconBluetoothHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates the RSSI channel and the Thing status according to the new received rssi value
 */
protected void updateRSSI() {
    if (device != null) {
        Integer rssi = device.getRssi();
        if (rssi != null && rssi != 0) {
            updateState(BluetoothBindingConstants.CHANNEL_TYPE_RSSI, new DecimalType(rssi));
            updateStatusBasedOnRssi(true);
        } else {
            updateState(BluetoothBindingConstants.CHANNEL_TYPE_RSSI, UnDefType.NULL);
            updateStatusBasedOnRssi(false);
        }
    }
}
 
Example #17
Source File: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void testChannelWithUPAndDOWNCommands(ChannelUID channelUID, Item item) {
    synchronized (channelUID) {
        // First we have to make sure that the item state is 0
        radioHandler.handleCommand(channelUID, DecimalType.valueOf("0"));
        waitForAssert(() -> {
            assertTrue("We should be able to turn on the radio",
                    radioServiceDummy.containsRequestParameter(1, CHANNEL_POWER));
            radioServiceDummy.clearRequestParameters();
        });

        radioHandler.handleCommand(channelUID, UpDownType.UP);
        waitForAssert(() -> {
            assertTrue("We should be able to increase the volume correctly",
                    radioServiceDummy.containsRequestParameter(1, VOLUME));
            radioServiceDummy.clearRequestParameters();
        });

        radioHandler.handleCommand(channelUID, UpDownType.DOWN);
        waitForAssert(() -> {
            assertTrue("We should be able to decrease the volume correctly",
                    radioServiceDummy.containsRequestParameter(0, VOLUME));
            radioServiceDummy.clearRequestParameters();
        });

        // Trying to decrease one more time
        radioHandler.handleCommand(channelUID, UpDownType.DOWN);
        waitForAssert(() -> {
            assertTrue("We shouldn't be able to decrease the volume below 0",
                    radioServiceDummy.areRequestParametersEmpty());
            radioServiceDummy.clearRequestParameters();
        });
    }
}
 
Example #18
Source File: DS2438Test.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void humidityChannel() {
    instantiateDevice();

    try {
        Mockito.when(mockBridgeHandler.checkPresence(testSensorId)).thenReturn(OnOffType.ON);
        Mockito.when(mockBridgeHandler.readDecimalType(eq(testSensorId), any())).thenReturn(new DecimalType(10.0));

        testDevice.enableChannel(CHANNEL_HUMIDITY);
        testDevice.enableChannel(CHANNEL_ABSOLUTE_HUMIDITY);
        testDevice.enableChannel(CHANNEL_DEWPOINT);
        testDevice.configureChannels();
        inOrder.verify(mockThingHandler).getThing();
        testDevice.refresh(mockBridgeHandler, true);

        inOrder.verify(mockBridgeHandler, times(2)).readDecimalType(eq(testSensorId), any());
        inOrder.verify(mockThingHandler).postUpdate(eq(CHANNEL_HUMIDITY), eq(new QuantityType<>("10.0 %")));
        inOrder.verify(mockThingHandler).postUpdate(eq(CHANNEL_ABSOLUTE_HUMIDITY),
                eq(new QuantityType<>("0.9381970824113001000 g/m³")));
        inOrder.verify(mockThingHandler).postUpdate(eq(CHANNEL_DEWPOINT),
                eq(new QuantityType<>("-20.31395053870025 °C")));

        inOrder.verifyNoMoreInteractions();
    } catch (OwException e) {
        Assert.fail("caught unexpected OwException");
    }
}
 
Example #19
Source File: ZoneTemperatureControlHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void sendCommandAndUpdateChannel(Float newValue) {
    if (isTemperature()) {
        if (temperatureSensorTransmitter.pushTargetTemperature(zoneID, newValue)) {
            currentValue = newValue;
            updateState(currentChannelID, new DecimalType(newValue));
        }
    } else {
        if (temperatureSensorTransmitter.pushControlValue(zoneID, newValue)) {
            currentValue = newValue;
            updateState(currentChannelID, new PercentType(newValue.intValue()));
        }
    }
}
 
Example #20
Source File: LightStateConverterTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void colorLightStateConverterForBrightnessConversionIsBijective() {
    final State lightState = new State();
    lightState.colormode = ColorMode.CT.toString();
    for (int percent = 1; percent <= 100; ++percent) {
        final HSBType hsbType = new HSBType(DecimalType.ZERO, PercentType.ZERO, new PercentType(percent));
        StateUpdate stateUpdate = LightStateConverter.toColorLightState(hsbType, lightState);
        assertThat(stateUpdate.commands.size(), is(3));
        assertThat(stateUpdate.commands.get(2).key, is("bri"));
        lightState.bri = Integer.parseInt(stateUpdate.commands.get(2).value.toString());
        assertThat(LightStateConverter.toHSBType(lightState).getBrightness().intValue(), is(percent));
    }
}
 
Example #21
Source File: LightStateConverterTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void colorLightStateConverterForSaturationConversionIsBijective() {
    final State lightState = new State();
    lightState.colormode = ColorMode.CT.toString();
    for (int percent = 0; percent <= 100; ++percent) {
        final HSBType hsbType = new HSBType(DecimalType.ZERO, new PercentType(percent), PercentType.HUNDRED);
        StateUpdate stateUpdate = LightStateConverter.toColorLightState(hsbType, lightState);
        assertThat(stateUpdate.commands.size(), is(3));
        assertThat(stateUpdate.commands.get(1).key, is("sat"));
        lightState.sat = Integer.parseInt(stateUpdate.commands.get(1).value.toString());
        assertThat(LightStateConverter.toHSBType(lightState).getSaturation().intValue(), is(percent));
    }
}
 
Example #22
Source File: HomieImplementationTests.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("null")
@Test
public void retrieveAttributes() throws InterruptedException, ExecutionException {
    assertThat(connection.hasSubscribers(), is(false));

    Node node = new Node(deviceTopic, "testnode", ThingChannelConstants.testHomieThing, callback,
            new NodeAttributes());
    Property property = spy(
            new Property(deviceTopic + "/testnode", node, "temperature", callback, new PropertyAttributes()));

    // Create a scheduler
    ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);

    property.subscribe(connection, scheduler, 100).get();

    assertThat(property.attributes.settable, is(true));
    assertThat(property.attributes.retained, is(true));
    assertThat(property.attributes.name, is("Testprop"));
    assertThat(property.attributes.unit, is("°C"));
    assertThat(property.attributes.datatype, is(DataTypeEnum.float_));
    assertThat(property.attributes.format, is("-100:100"));
    verify(property).attributesReceived();

    // Receive property value
    ChannelState channelState = spy(property.getChannelState());
    PropertyHelper.setChannelState(property, channelState);

    property.startChannel(connection, scheduler, 200).get();
    verify(channelState).start(any(), any(), anyInt());
    verify(channelState).processMessage(any(), any());
    verify(callback).updateChannelState(any(), any());

    assertThat(property.getChannelState().getCache().getChannelState(), is(new DecimalType(10)));

    property.stop().get();
    assertThat(connection.hasSubscribers(), is(false));
}
 
Example #23
Source File: NumberItem.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Try to convert a {@link DecimalType} into a new {@link QuantityType}. The unit for the new
 * type is derived either from the state description (which might also give a hint on items w/o dimension) or from
 * the system default unit of the given dimension.
 *
 * @param originalType the source {@link DecimalType}.
 * @param dimension the dimension to which the new {@link QuantityType} should adhere.
 * @return the new {@link QuantityType} from the given originalType, {@code null} if a unit could not be calculated.
 */
public @Nullable QuantityType<?> toQuantityType(DecimalType originalType,
        @Nullable Class<? extends Quantity<?>> dimension) {
    Unit<? extends Quantity<?>> itemUnit = getUnit(dimension);
    if (itemUnit != null) {
        return new QuantityType<>(originalType.toBigDecimal(), itemUnit);
    }

    return null;
}
 
Example #24
Source File: NumberValue.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public NumberValue(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal step) {
    super(CoreItemFactory.NUMBER, Stream.of(DecimalType.class, IncreaseDecreaseType.class, UpDownType.class)
            .collect(Collectors.toList()));
    this.min = min;
    this.max = max;
    this.step = step == null ? new BigDecimal(1.0) : step;
}
 
Example #25
Source File: WemoHandlerTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertThatChannelLASTONFORIsUpdatedOnReceivedValue() {
    insightParams.lastOnFor = TIME_PARAM;
    State expectedStateType = new DecimalType(TIME_PARAM);
    String expectedChannel = CHANNEL_LASTONFOR;

    testOnValueReceived(expectedChannel, expectedStateType, insightParams.toString());
}
 
Example #26
Source File: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verify OFFLINE Thing status when the HTTP response cannot be parsed correctly.
 */
@Test
public void offlineIfParseError() {
    // create a thing with two channels - the power channel and any of the others
    String modeChannelID = FSInternetRadioBindingConstants.CHANNEL_MODE;
    String acceptedItemType = acceptedItemTypes.get(modeChannelID);
    createChannel(DEFAULT_THING_UID, modeChannelID, acceptedItemType);

    Thing radioThing = initializeRadioThing(DEFAULT_COMPLETE_CONFIGURATION);
    testRadioThingConsideringConfiguration(radioThing);

    ChannelUID modeChannelUID = getChannelUID(radioThing, modeChannelID);

    /*
     * Setting the isInvalidResponseExpected variable to true
     * in order to get the incorrect XML response from the servlet
     */
    radioServiceDummy.setInvalidResponse(true);

    // try to handle a command
    radioHandler.handleCommand(modeChannelUID, DecimalType.valueOf("1"));

    waitForAssert(() -> {
        String exceptionMessage = "java.io.IOException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2;";
        verifyCommunicationError(exceptionMessage);
    });
    radioServiceDummy.setInvalidResponse(false);
}
 
Example #27
Source File: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verify the mode channel is updated.
 */
@Test
public void modeChannelUdpated() {
    String modeChannelID = FSInternetRadioBindingConstants.CHANNEL_MODE;
    String acceptedItemType = acceptedItemTypes.get(modeChannelID);
    createChannel(DEFAULT_THING_UID, modeChannelID, acceptedItemType);

    Thing radioThing = initializeRadioThing(DEFAULT_COMPLETE_CONFIGURATION);
    testRadioThingConsideringConfiguration(radioThing);

    turnTheRadioOn(radioThing);

    ChannelUID modeChannelUID = getChannelUID(radioThing, modeChannelID);
    initializeItem(modeChannelUID, DEFAULT_TEST_ITEM_NAME, acceptedItemType);

    radioHandler.handleCommand(modeChannelUID, DecimalType.valueOf("1"));
    waitForAssert(() -> {
        assertTrue("We should be able to update the mode channel correctly",
                radioServiceDummy.containsRequestParameter(1, CHANNEL_MODE));
        radioServiceDummy.clearRequestParameters();
    });

    /*
     * Setting the needed boolean variable to true, so we can be sure
     * that an invalid value will be returned in the XML response
     */
    radioHandler.handleCommand(modeChannelUID, DecimalType.valueOf("3"));
    waitForAssert(() -> {
        assertTrue("We should be able to update the mode channel correctly",
                radioServiceDummy.containsRequestParameter(3, CHANNEL_MODE));
        radioServiceDummy.clearRequestParameters();
    });
}
 
Example #28
Source File: SwitchItemTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getAsDecimalFromSwitch() {
    SwitchItem item = new SwitchItem("Test");
    item.setState(OnOffType.ON);
    assertEquals(new DecimalType(1), item.getStateAs(DecimalType.class));
    item.setState(OnOffType.OFF);
    assertEquals(new DecimalType(0), item.getStateAs(DecimalType.class));
}
 
Example #29
Source File: ItemStateConverterImplTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void numberItemWithoutDimensionShouldConvertToDecimalType() {
    Item item = new NumberItem("number");
    State originalState = new QuantityType<>("12.34 °C");
    State convertedState = itemStateConverter.convertToAcceptedState(originalState, item);

    assertThat(convertedState, is(new DecimalType("12.34")));
}
 
Example #30
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);
        }
    }
}