org.eclipse.smarthome.core.types.State Java Examples

The following examples show how to use org.eclipse.smarthome.core.types.State. 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: DateTimeGroupFunctionTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEarliestFunction() {

    ZonedDateTime expectedDateTime = ZonedDateTime.now();
    items.add(new TestItem("TestItem1", new DateTimeType(expectedDateTime)));
    items.add(new TestItem("TestItem2", UnDefType.UNDEF));
    items.add(new TestItem("TestItem3", new DateTimeType(expectedDateTime.plusDays(10))));
    items.add(new TestItem("TestItem4", new DateTimeType(expectedDateTime.plusYears(1))));
    items.add(new TestItem("TestItem5", UnDefType.UNDEF));
    items.add(new TestItem("TestItem6", new DateTimeType(expectedDateTime.plusSeconds(1))));

    function = new DateTimeGroupFunction.Earliest();
    State state = function.calculate(items);

    assertTrue(expectedDateTime.isEqual(((DateTimeType) state).getZonedDateTime()));
}
 
Example #2
Source File: GroupItemTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void assertThatGroupItemWithRollershutterBaseItemConversionWorks() {
    // initially this group has State UndefType.NULL
    GroupItem groupItem = new GroupItem("root", new RollershutterItem("myRollerShutter"));
    State groupStateAsOnOff = groupItem.getStateAs(OnOffType.class);

    // a state conversion from NULL to OnOffType should not be possible
    assertNull(groupStateAsOnOff);

    // init group
    groupItem.setState(new PercentType(70));
    groupStateAsOnOff = groupItem.getStateAs(OnOffType.class);

    // any value >0 means on, so 50% means the group state should be ON
    assertTrue(OnOffType.ON.equals(groupStateAsOnOff));
}
 
Example #3
Source File: ScriptTypeComputer.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(final QuantityLiteral assignment, ITypeComputationState state) {
    LightweightTypeReference qt = null;
    for (ITypeExpectation exp : state.getExpectations()) {
        if (exp.getExpectedType() == null) {
            continue;
        }

        if (exp.getExpectedType().isType(Number.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
        if (exp.getExpectedType().isType(State.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
        if (exp.getExpectedType().isType(Command.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
    }
    if (qt == null) {
        qt = getRawTypeForName(QuantityType.class, state);
    }
    state.acceptActualType(qt);
}
 
Example #4
Source File: GenericItem.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
protected void notifyListeners(final State oldState, final State newState) {
    // if nothing has changed, we send update notifications
    Set<StateChangeListener> clonedListeners = null;
    clonedListeners = new CopyOnWriteArraySet<StateChangeListener>(listeners);
    ExecutorService pool = ThreadPoolManager.getPool(ITEM_THREADPOOLNAME);
    for (final StateChangeListener listener : clonedListeners) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    listener.stateUpdated(GenericItem.this, newState);
                    if (newState != null && !newState.equals(oldState)) {
                        listener.stateChanged(GenericItem.this, oldState, newState);
                    }
                } catch (Exception e) {
                    logger.warn("failed notifying listener '{}' about state update of item {}: {}", listener,
                            GenericItem.this.getName(), e.getMessage(), e);
                }
            }
        });
    }
}
 
Example #5
Source File: BusEvent.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Posts a status update for a specified item to the event bus.
 *
 * @param itemName the name of the item to send the status update for
 * @param stateAsString the new state of the item
 */
static public Object postUpdate(String itemName, String stateString) {
    ItemRegistry registry = ScriptServiceUtil.getItemRegistry();
    EventPublisher publisher = ScriptServiceUtil.getEventPublisher();
    if (publisher != null && registry != null) {
        try {
            Item item = registry.getItem(itemName);
            State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString);
            if (state != null) {
                publisher.post(ItemEventFactory.createStateEvent(itemName, state));
            } else {
                LoggerFactory.getLogger(BusEvent.class).warn(
                        "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName,
                        getAcceptedDataTypeNames(item));
            }
        } catch (ItemNotFoundException e) {
            LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName);
        }
    }
    return null;
}
 
Example #6
Source File: SystemOffsetProfileTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testQuantityTypeOnStateUpdateFromHandlerFahrenheitOffset() {
    ProfileCallback callback = mock(ProfileCallback.class);
    SystemOffsetProfile offsetProfile = createProfile(callback, "3 °F");

    State state = new QuantityType<Temperature>("23 °C");
    offsetProfile.onStateUpdateFromHandler(state);

    ArgumentCaptor<State> capture = ArgumentCaptor.forClass(State.class);
    verify(callback, times(1)).sendUpdate(capture.capture());

    State result = capture.getValue();
    @SuppressWarnings("unchecked")
    QuantityType<Temperature> decResult = (QuantityType<Temperature>) result;
    assertThat(decResult.doubleValue(), is(closeTo(24.6666666666666666666666666666667d, 0.0000000000000001d)));
    assertEquals(SIUnits.CELSIUS, decResult.getUnit());
}
 
Example #7
Source File: DateTimeGroupFunction.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public State calculate(Set<Item> items) {
    if (items != null && items.size() > 0) {
        ZonedDateTime max = null;
        for (Item item : items) {
            DateTimeType itemState = item.getStateAs(DateTimeType.class);
            if (itemState != null) {
                if (max == null || max.isBefore(itemState.getZonedDateTime())) {
                    max = itemState.getZonedDateTime();
                }
            }
        }
        if (max != null) {
            return new DateTimeType(max);
        }
    }
    return UnDefType.UNDEF;
}
 
Example #8
Source File: SystemOffsetProfileTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testQuantityTypeOnStateUpdateFromItem() {
    ProfileCallback callback = mock(ProfileCallback.class);
    SystemOffsetProfile offsetProfile = createProfile(callback, "3°C");

    State state = new QuantityType<Temperature>("23°C");
    offsetProfile.onStateUpdateFromItem(state);

    ArgumentCaptor<State> capture = ArgumentCaptor.forClass(State.class);
    verify(callback, times(1)).handleUpdate(capture.capture());

    State result = capture.getValue();
    @SuppressWarnings("unchecked")
    QuantityType<Temperature> decResult = (QuantityType<Temperature>) result;
    assertEquals(20, decResult.intValue());
    assertEquals(SIUnits.CELSIUS, decResult.getUnit());
}
 
Example #9
Source File: ArithmeticGroupFunction.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public State calculate(Set<Item> items) {
    BigDecimal sum = BigDecimal.ZERO;
    int count = 0;
    if (items != null) {
        for (Item item : items) {
            DecimalType itemState = item.getStateAs(DecimalType.class);
            if (itemState != null) {
                sum = sum.add(itemState.toBigDecimal());
                count++;
            }
        }
    }
    if (count > 0) {
        return new DecimalType(sum.divide(BigDecimal.valueOf(count), RoundingMode.HALF_UP));
    } else {
        return UnDefType.UNDEF;
    }
}
 
Example #10
Source File: DS2423Test.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void counterChannelTest() {
    instantiateDevice();

    List<State> returnValue = new ArrayList<>();
    returnValue.add(new DecimalType(1408));
    returnValue.add(new DecimalType(3105));

    try {
        Mockito.when(mockBridgeHandler.checkPresence(testSensorId)).thenReturn(OnOffType.ON);
        Mockito.when(mockBridgeHandler.readDecimalTypeArray(eq(testSensorId), any())).thenReturn(returnValue);

        testDevice.configureChannels();
        testDevice.refresh(mockBridgeHandler, true);

        inOrder.verify(mockBridgeHandler, times(1)).readDecimalTypeArray(eq(testSensorId), any());
        inOrder.verify(mockThingHandler).postUpdate(eq(channelName(0)), eq(returnValue.get(0)));
        inOrder.verify(mockThingHandler).postUpdate(eq(channelName(1)), eq(returnValue.get(1)));
    } catch (OwException e) {
        Assert.fail("caught unexpected OwException");
    }
}
 
Example #11
Source File: WemoCoffeeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public State getDateTimeState(String attributeValue) {
    if (attributeValue != null) {
        long value = 0;
        try {
            value = Long.parseLong(attributeValue) * 1000; // convert s to ms
        } catch (NumberFormatException e) {
            logger.error("Unable to parse attributeValue '{}' for device '{}'; expected long", attributeValue,
                    getThing().getUID());
            return null;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(value),
                TimeZone.getDefault().toZoneId());
        State dateTimeState = new DateTimeType(zoned);
        if (dateTimeState != null) {
            logger.trace("New attribute brewed '{}' received", dateTimeState);
            return dateTimeState;
        }
    }
    return null;
}
 
Example #12
Source File: ComponentLight.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Proxy method to condense all three MQTT subscriptions to one channel
 */
@Override
public void updateChannelState(ChannelUID channelUID, State value) {
    ChannelStateUpdateListener listener = channelStateUpdateListener;
    if (listener != null) {
        listener.updateChannelState(colorChannel.channelUID, value);
    }
}
 
Example #13
Source File: OwserverConnection.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * read a decimal type
 *
 * @param path full owfs path to sensor
 * @return DecimalType if successful
 * @throws OwException
 */
public State readDecimalType(String path) throws OwException {
    State returnState = UnDefType.UNDEF;
    OwserverPacket requestPacket = new OwserverPacket(OwserverMessageType.READ, path);

    OwserverPacket returnPacket = request(requestPacket);
    if ((returnPacket.getReturnCode() != -1) && returnPacket.hasPayload()) {
        returnState = DecimalType.valueOf(returnPacket.getPayloadString().trim());
    } else {
        throw new OwException("invalid or empty packet");
    }

    return returnState;
}
 
Example #14
Source File: AbstractWidgetRenderer.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected String getState(Widget w) {
    State state = itemUIRegistry.getState(w);
    if (state != null) {
        return state.toString();
    } else {
        return "NULL";
    }
}
 
Example #15
Source File: QuantityTypeArithmeticGroupFunctionTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaxFunctionQuantityType() {
    items.add(createNumberItem("TestItem1", Temperature.class, new QuantityType<Temperature>("100 °C")));
    items.add(createNumberItem("TestItem2", Temperature.class, UnDefType.NULL));
    items.add(createNumberItem("TestItem3", Temperature.class, new QuantityType<Temperature>("200 °C")));
    items.add(createNumberItem("TestItem4", Temperature.class, UnDefType.UNDEF));
    items.add(createNumberItem("TestItem5", Temperature.class, new QuantityType<Temperature>("300 °C")));

    function = new QuantityTypeArithmeticGroupFunction.Max(Temperature.class);
    State state = function.calculate(items);

    assertEquals(new QuantityType<Temperature>("300 °C"), state);
}
 
Example #16
Source File: ArithmeticGroupFunction.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public State calculate(Set<Item> items) {
    if (items != null && items.size() > 0) {
        for (Item item : items) {
            if (!activeState.equals(item.getStateAs(activeState.getClass()))) {
                return passiveState;
            }
        }
        return activeState;
    } else {
        // if we do not have any items, we return the passive state
        return passiveState;
    }
}
 
Example #17
Source File: RuleEngineImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected synchronized void executeRules(Iterable<Rule> rules, Item item, State oldState) {
    for (Rule rule : rules) {
        RuleEvaluationContext context = new RuleEvaluationContext();
        context.newValue(QualifiedName.create(RulesJvmModelInferrer.VAR_TRIGGERING_ITEM), item);
        context.newValue(QualifiedName.create(RulesJvmModelInferrer.VAR_PREVIOUS_STATE), oldState);
        executeRule(rule, context);
    }
}
 
Example #18
Source File: QuantityTypeArithmeticGroupFunctionTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaxFunctionQuantityTypeIncompatibleUnits() {
    items.add(createNumberItem("TestItem1", Temperature.class, new QuantityType<Temperature>("23.54 °C")));
    items.add(createNumberItem("TestItem2", Temperature.class, UnDefType.NULL));
    items.add(createNumberItem("TestItem3", Pressure.class, new QuantityType<Pressure>("192.2 hPa")));

    function = new QuantityTypeArithmeticGroupFunction.Max(Temperature.class);
    State state = function.calculate(items);

    assertEquals(new QuantityType<Temperature>("23.54 °C"), state);
}
 
Example #19
Source File: SystemOffsetProfileTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDecimalTypeOnStateUpdateFromItem() {
    ProfileCallback callback = mock(ProfileCallback.class);
    SystemOffsetProfile offsetProfile = createProfile(callback, "3");

    State state = new DecimalType(23);
    offsetProfile.onStateUpdateFromItem(state);

    ArgumentCaptor<State> capture = ArgumentCaptor.forClass(State.class);
    verify(callback, times(1)).handleUpdate(capture.capture());

    State result = capture.getValue();
    DecimalType decResult = (DecimalType) result;
    assertEquals(20, decResult.intValue());
}
 
Example #20
Source File: ItemStateConverterImplTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStateConversion() {
    Item item = new NumberItem("number");
    State originalState = new PercentType("42");
    State convertedState = itemStateConverter.convertToAcceptedState(originalState, item);

    assertThat(convertedState, is(new DecimalType("0.42")));
}
 
Example #21
Source File: ItemRegistryDelegate.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Set<java.util.Map.Entry<String, State>> entrySet() {
    Set<Map.Entry<String, State>> entries = new HashSet<Map.Entry<String, State>>();
    for (Item item : itemRegistry.getAll()) {
        entries.add(new AbstractMap.SimpleEntry<>(item.getName(), item.getState()));
    }
    return entries;
}
 
Example #22
Source File: SelectionRenderer.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private String buildRow(Selection w, String lab, String cmd, Item item, State state, StringBuilder rowSB)
        throws RenderException {
    String mappingLabel = null;
    String rowSnippet = getSnippet("selection_row");

    String command = cmd != null ? cmd : "";
    String label = lab;

    if (item instanceof NumberItem && ((NumberItem) item).getDimension() != null) {
        String unit = getUnitForWidget(w);
        command = StringUtils.replace(command, UnitUtils.UNIT_PLACEHOLDER, unit);
        label = StringUtils.replace(label, UnitUtils.UNIT_PLACEHOLDER, unit);
    }

    rowSnippet = StringUtils.replace(rowSnippet, "%item%", w.getItem() != null ? w.getItem() : "");
    rowSnippet = StringUtils.replace(rowSnippet, "%cmd%", escapeHtml(command));
    rowSnippet = StringUtils.replace(rowSnippet, "%label%", label != null ? escapeHtml(label) : "");

    State compareMappingState = state;
    if (state instanceof QuantityType) { // convert the item state to the command value for proper
                                         // comparison and "checked" attribute calculation
        compareMappingState = convertStateToLabelUnit((QuantityType<?>) state, command);
    }

    if (compareMappingState.toString().equals(command)) {
        mappingLabel = label;
        rowSnippet = StringUtils.replace(rowSnippet, "%checked%", "checked=\"true\"");
    } else {
        rowSnippet = StringUtils.replace(rowSnippet, "%checked%", "");
    }

    rowSB.append(rowSnippet);

    return mappingLabel;
}
 
Example #23
Source File: QuantityTypeArithmeticGroupFunctionTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAvgFunctionQuantityType() {
    items.add(createNumberItem("TestItem1", Temperature.class, new QuantityType<Temperature>("100 °C")));
    items.add(createNumberItem("TestItem2", Temperature.class, UnDefType.NULL));
    items.add(createNumberItem("TestItem3", Temperature.class, new QuantityType<Temperature>("200 °C")));
    items.add(createNumberItem("TestItem4", Temperature.class, UnDefType.UNDEF));
    items.add(createNumberItem("TestItem5", Temperature.class, new QuantityType<Temperature>("300 °C")));

    function = new QuantityTypeArithmeticGroupFunction.Avg(Temperature.class);
    State state = function.calculate(items);

    assertEquals(new QuantityType<Temperature>("200 °C"), state);
}
 
Example #24
Source File: ScriptBusEvent.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Restores item states from a map.
 * If the saved state can be interpreted as a command, a command is sent for the item
 * (and the physical device can send a status update if occurred). If it is no valid
 * command, the item state is directly updated to the saved value.
 *
 * @param statesMap a map with ({@link Item}, {@link State}) entries
 * @return null
 */
public Object restoreStates(Map<Item, State> statesMap) {
    if (statesMap != null) {
        for (Entry<Item, State> entry : statesMap.entrySet()) {
            if (entry.getValue() instanceof Command) {
                sendCommand(entry.getKey(), (Command) entry.getValue());
            } else {
                postUpdate(entry.getKey(), entry.getValue());
            }
        }
    }
    return null;
}
 
Example #25
Source File: LocationItem.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setState(State state) {
    if (isAcceptedState(acceptedDataTypes, state)) {
        super.setState(state);
    } else {
        logSetTypeError(state);
    }
}
 
Example #26
Source File: OwserverBridgeHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public State readDecimalType(SensorId sensorId, OwDeviceParameterMap parameter) throws OwException {
    synchronized (owserverConnection) {
        return owserverConnection
                .readDecimalType(((OwserverDeviceParameter) parameter.get(THING_TYPE_OWSERVER)).getPath(sensorId));
    }
}
 
Example #27
Source File: ConvertFromBindingTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDecimalTypeConverter() throws ConverterException {
    State convertedState;
    TypeConverter<?> decimalConverter = ConverterFactory.createConverter("Number");

    // the binding is backwards compatible, so clients may still use DecimalType, even if a unit is used
    floatDp.setUnit("%");

    floatDp.setValue(99.9);
    convertedState = decimalConverter.convertFromBinding(floatDp);
    assertThat(convertedState, instanceOf(DecimalType.class));
    assertThat(((DecimalType) convertedState).doubleValue(), is(99.9));

    floatDp.setValue(77.77777778);
    convertedState = decimalConverter.convertFromBinding(floatDp);
    assertThat(convertedState, instanceOf(DecimalType.class));
    assertThat(((DecimalType) convertedState).doubleValue(), is(77.777778));

    integerDp.setValue(99.0);
    convertedState = decimalConverter.convertFromBinding(integerDp);
    assertThat(convertedState, instanceOf(DecimalType.class));
    assertThat(((DecimalType) convertedState).doubleValue(), is(99.0));

    integerDp.setValue(99.9);
    convertedState = decimalConverter.convertFromBinding(integerDp);
    assertThat(convertedState, instanceOf(DecimalType.class));
    assertThat(((DecimalType) convertedState).doubleValue(), is(99.0));
}
 
Example #28
Source File: GroupFunction.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T extends State> T getStateAs(Set<Item> items, Class<T> stateClass) {
    State state = calculate(items);
    if (stateClass.isInstance(state)) {
        return stateClass.cast(state);
    } else {
        return null;
    }
}
 
Example #29
Source File: ItemUIRegistryImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Converts an item state to the type the widget supports (if possible)
 *
 * @param w Widget in sitemap that shows the state
 * @param i item
 * @param state
 * @return the converted state or the original if conversion was not possible
 */
@Override
public State convertState(Widget w, Item i, State state) {
    State returnState = null;

    State itemState = i.getState();
    if (itemState instanceof QuantityType) {
        itemState = convertStateToWidgetUnit((QuantityType<?>) itemState, w);
    }

    if (w instanceof Switch && i instanceof RollershutterItem) {
        // RollerShutter are represented as Switch in a Sitemap but need a PercentType state
        returnState = itemState.as(PercentType.class);
    } else if (w instanceof Slider) {
        if (i.getAcceptedDataTypes().contains(PercentType.class)) {
            returnState = itemState.as(PercentType.class);
        } else {
            returnState = itemState.as(DecimalType.class);
        }
    } else if (w instanceof Switch) {
        Switch sw = (Switch) w;
        if (sw.getMappings().size() == 0) {
            returnState = itemState.as(OnOffType.class);
        }
    }

    // if returnState is null, a conversion was not possible
    if (returnState == null) {
        // we return the original state to not break anything
        returnState = itemState;
    }
    return returnState;
}
 
Example #30
Source File: SystemOffsetProfileTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDecimalTypeOnStateUpdateFromHandler() {
    ProfileCallback callback = mock(ProfileCallback.class);
    SystemOffsetProfile offsetProfile = createProfile(callback, "3");

    State state = new DecimalType(23);
    offsetProfile.onStateUpdateFromHandler(state);

    ArgumentCaptor<State> capture = ArgumentCaptor.forClass(State.class);
    verify(callback, times(1)).sendUpdate(capture.capture());

    State result = capture.getValue();
    DecimalType decResult = (DecimalType) result;
    assertEquals(26, decResult.intValue());
}