Search in sources :

Example 11 with DecimalType

use of org.openhab.core.library.types.DecimalType in project openhab1-addons by openhab.

the class WemoBinding method execute.

/**
     * @{inheritDoc}
     */
@Override
protected void execute() {
    logger.debug("execute() method is called!");
    for (WemoBindingProvider provider : providers) {
        for (String itemName : provider.getItemNames()) {
            logger.debug("Wemo item '{}' state will be updated", itemName);
            try {
                if (provider.getUDN(itemName).toLowerCase().contains("insight")) {
                    String insightParams = getInsightParams(itemName);
                    if (insightParams != null) {
                        String[] splitInsightParams = insightParams.split("\\|");
                        if (splitInsightParams[0] != null) {
                            if (provider.getChannelType(itemName).equals(WemoChannelType.state)) {
                                OnOffType binaryState = null;
                                binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON;
                                if (binaryState != null) {
                                    logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState, itemName);
                                    eventPublisher.postUpdate(itemName, binaryState);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.lastChangedAt)) {
                                long lastChangedAt = 0;
                                try {
                                    // convert s to ms
                                    lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000;
                                } catch (NumberFormatException e) {
                                    logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long", splitInsightParams[1], itemName);
                                }
                                GregorianCalendar cal = new GregorianCalendar();
                                cal.setTimeInMillis(lastChangedAt);
                                State lastChangedAtState = new DateTimeType(cal);
                                if (lastChangedAt != 0) {
                                    logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState, itemName);
                                    eventPublisher.postUpdate(itemName, lastChangedAtState);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.lastOnFor)) {
                                State lastOnFor = DecimalType.valueOf(splitInsightParams[2]);
                                if (lastOnFor != null) {
                                    logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor, itemName);
                                    eventPublisher.postUpdate(itemName, lastOnFor);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.onToday)) {
                                State onToday = DecimalType.valueOf(splitInsightParams[3]);
                                if (onToday != null) {
                                    logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday, itemName);
                                    eventPublisher.postUpdate(itemName, onToday);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.onTotal)) {
                                State onTotal = DecimalType.valueOf(splitInsightParams[4]);
                                if (onTotal != null) {
                                    logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal, itemName);
                                    eventPublisher.postUpdate(itemName, onTotal);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.timespan)) {
                                State timespan = DecimalType.valueOf(splitInsightParams[5]);
                                if (timespan != null) {
                                    logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan, itemName);
                                    eventPublisher.postUpdate(itemName, timespan);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.averagePower)) {
                                // natively given
                                State averagePower = DecimalType.valueOf(splitInsightParams[6]);
                                // in W
                                if (averagePower != null) {
                                    logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower, itemName);
                                    eventPublisher.postUpdate(itemName, averagePower);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.currentPower)) {
                                BigDecimal currentMW = new BigDecimal(splitInsightParams[7]);
                                State currentPower = new DecimalType(// recalculate
                                currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP));
                                // mW to W
                                if (currentPower != null) {
                                    logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower, itemName);
                                    eventPublisher.postUpdate(itemName, currentPower);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.energyToday)) {
                                BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]);
                                // recalculate mW-mins to Wh
                                State energyToday = new DecimalType(energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
                                if (energyToday != null) {
                                    logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday, itemName);
                                    eventPublisher.postUpdate(itemName, energyToday);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.energyTotal)) {
                                BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]);
                                // recalculate mW-mins to Wh
                                State energyTotal = new DecimalType(energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
                                if (energyTotal != null) {
                                    logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal, itemName);
                                    eventPublisher.postUpdate(itemName, energyTotal);
                                }
                            }
                            if (provider.getChannelType(itemName).equals(WemoChannelType.standbyLimit)) {
                                BigDecimal standbyLimitMW = new BigDecimal(splitInsightParams[10]);
                                // recalculate mW to W
                                State standbyLimit = new DecimalType(standbyLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP));
                                if (standbyLimit != null) {
                                    logger.trace("New InsightParam standbyLimit '{}' for device '{}' received", standbyLimit, itemName);
                                    eventPublisher.postUpdate(itemName, standbyLimit);
                                }
                            }
                        }
                    }
                } else {
                    String state = getWemoState(itemName);
                    if (state != null) {
                        if (provider.getUDN(itemName).toLowerCase().contains("motion")) {
                            State newState = state.equals("0") ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                            eventPublisher.postUpdate(itemName, newState);
                        } else {
                            State itemState = state.equals("0") ? OnOffType.OFF : OnOffType.ON;
                            eventPublisher.postUpdate(itemName, itemState);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("Error in execute method: " + e.getMessage(), e);
            }
        }
    }
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) WemoBindingProvider(org.openhab.binding.wemo.WemoBindingProvider) OnOffType(org.openhab.core.library.types.OnOffType) State(org.openhab.core.types.State) GregorianCalendar(java.util.GregorianCalendar) DecimalType(org.openhab.core.library.types.DecimalType) BigDecimal(java.math.BigDecimal) ConfigurationException(org.osgi.service.cm.ConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 12 with DecimalType

use of org.openhab.core.library.types.DecimalType in project openhab1-addons by openhab.

the class VarAbs method visualizationVarStatus.

/**
     * Visualization for {@link StringType} and {@link DecimalType}.
     * {@inheritDoc}
     */
@Override
public boolean visualizationVarStatus(ModStatusVar pchkInput, Command cmd, Item item, EventPublisher eventPublisher) {
    // current value.
    if (pchkInput.getLogicalSourceAddr().equals(this.addr) && pchkInput.getVar() == this.var) {
        if (item.getAcceptedDataTypes().contains(StringType.class)) {
            String valueStr = pchkInput.getValue().toVarUnitString(this.unit, LcnDefs.Var.isLockableRegulatorSource(this.var), LcnDefs.Var.useLcnSpecialValues(this.var));
            eventPublisher.postUpdate(item.getName(), new StringType(valueStr));
            return true;
        } else if (item.getAcceptedDataTypes().contains(DecimalType.class)) {
            eventPublisher.postUpdate(item.getName(), new DecimalType(pchkInput.getValue().toVarUnit(this.unit, LcnDefs.Var.isLockableRegulatorSource(this.var))));
            return true;
        }
    }
    return false;
}
Also used : StringType(org.openhab.core.library.types.StringType) DecimalType(org.openhab.core.library.types.DecimalType)

Example 13 with DecimalType

use of org.openhab.core.library.types.DecimalType in project openhab1-addons by openhab.

the class LightwaverfConvertorTest method testConvertToLightwaveRfMessageSetTempCommand.

@Test
public void testConvertToLightwaveRfMessageSetTempCommand() throws Exception {
    LightwaverfConvertor convertor = new LightwaverfConvertor();
    LightwaveRFCommand command = convertor.convertToLightwaveRfMessage("2", null, LightwaveRfType.HEATING_SET_TEMP, new DecimalType(21.5));
    LightwaveRFCommand expected = new LightwaveRfSetHeatingTemperatureCommand("200,!R2DhF*tP21.5");
    assertEquals(expected.getLightwaveRfCommandString(), command.getLightwaveRfCommandString());
}
Also used : LightwaveRfSetHeatingTemperatureCommand(org.openhab.binding.lightwaverf.internal.command.LightwaveRfSetHeatingTemperatureCommand) DecimalType(org.openhab.core.library.types.DecimalType) LightwaveRFCommand(org.openhab.binding.lightwaverf.internal.command.LightwaveRFCommand) Test(org.junit.Test)

Example 14 with DecimalType

use of org.openhab.core.library.types.DecimalType in project openhab1-addons by openhab.

the class OpenPathsBinding method execute.

/**
     * @{inheritDoc
     */
@Override
public void execute() {
    if (!bindingsExist()) {
        logger.debug("There is no existing OpenPaths binding configuration => refresh cycle aborted!");
        return;
    }
    for (OpenPathsBindingProvider provider : providers) {
        for (String itemName : provider.getItemNames()) {
            logger.trace("try binding provider item: " + itemName);
            OpenPathsBindingConfig bindingConfig = provider.getItemConfig(itemName);
            String bindingConfigName = bindingConfig.getName();
            String[] bindingParts = bindingConfigName.split("\\:");
            if (bindingParts.length < 1) {
                logger.error("Empty OpenPaths binding config");
                continue;
            }
            String name = bindingParts[0];
            if (!openPathsUsers.containsKey(name)) {
                logger.warn("There is no OpenPaths user configured for '" + name + "'. Please add this user to the binding configuration, including both the ACCESS_KEY and SECRET_KEY from the OpenPaths profile.");
                continue;
            }
            Location location = null;
            OpenPathsUser openPathsUser = openPathsUsers.get(name);
            if (openPathsUser.lastUpdateTS + this.refreshInterval < System.currentTimeMillis()) {
                String accessKey = openPathsUser.getAccessKey();
                String secretKey = openPathsUser.getSecretKey();
                if (StringUtils.isEmpty(accessKey)) {
                    logger.warn("There is no ACCESS_KEY configured for '" + name + "'. Please add this user to the binding configuration, including both the ACCESS_KEY and SECRET_KEY from the OpenPaths profile.");
                    continue;
                }
                if (StringUtils.isEmpty(secretKey)) {
                    logger.warn("There is no SECRET_KEY configured for '" + name + "'. Please add this user to the binding configuration, including both the ACCESS_KEY and SECRET_KEY from the OpenPaths profile.");
                    continue;
                }
                logger.debug("Requesting location for '{}'...", name);
                location = getUserLocation(accessKey, secretKey);
                if (location != null) {
                    openPathsUsers.get(name).setLastLocation(location);
                    logger.debug("New location received for '{}': {}", name, location.toString());
                } else {
                    logger.warn("Unable to determine location for '{}'. Skipping.", name);
                    continue;
                }
            } else {
                location = openPathsUsers.get(name).getLastLocation();
                logger.trace("Using cached location for '{}'", openPathsUser.toString());
            }
            String bindingLocationName = bindingParts.length > 1 ? bindingParts[1] : "";
            if (bindingLocationName.startsWith("current")) {
                if (bindingLocationName.equals("currentLocation")) {
                    eventPublisher.postUpdate(itemName, new StringType("" + location.getLatitude() + ", " + location.getLongitude()));
                } else if (bindingLocationName.equals("currentLatitude")) {
                    eventPublisher.postUpdate(itemName, new DecimalType(new BigDecimal(location.getLatitude())));
                } else if (bindingLocationName.equals("currentLongitude")) {
                    eventPublisher.postUpdate(itemName, new DecimalType(new BigDecimal(location.getLongitude())));
                } else {
                    logger.warn("unsupported Binding: " + bindingLocationName);
                }
                continue;
            }
            if (!locations.containsKey(bindingLocationName)) {
                logger.warn("location name " + bindingLocationName + " not configured, falling back to 'home'");
                bindingLocationName = "home";
            }
            logger.debug("OpenPathsUser: " + name + "@" + bindingLocationName);
            LocationBindingType bindingType = LocationBindingType.on;
            if (bindingParts.length == 3) {
                if (bindingParts[2].equals("distance")) {
                    bindingType = LocationBindingType.distance;
                }
            }
            Location bindingLocation = locations.get(bindingLocationName);
            logger.trace("Calculating distance between home ({}) and user location ({}) for '{}'...", new Object[] { bindingLocation.toString(), location.toString(), name });
            double distance = calculateDistance(bindingLocation, location);
            bindingLocation.setDistance(distance);
            logger.trace("Distance calculated as {} for '{}'@'{}'", distance, name, bindingLocationName);
            if (bindingType.equals(LocationBindingType.on)) {
                float fence = bindingLocation.getGeofence() == 0.0 ? geoFence : bindingLocation.getGeofence();
                if (distance <= fence) {
                    logger.trace("Detected that '{}'@'{}' is inside the geofence ({}m)", name, bindingLocationName, fence);
                    eventPublisher.postUpdate(itemName, OnOffType.ON);
                } else {
                    logger.trace("Detected that '{}'@'{}' is outside the geofence ({}m)", name, bindingLocationName, fence);
                    eventPublisher.postUpdate(itemName, OnOffType.OFF);
                }
            } else if (bindingType.equals(LocationBindingType.distance)) {
                eventPublisher.postUpdate(itemName, new DecimalType(new BigDecimal(distance / 1000)));
            }
        }
    }
}
Also used : StringType(org.openhab.core.library.types.StringType) DecimalType(org.openhab.core.library.types.DecimalType) BigDecimal(java.math.BigDecimal) OpenPathsBindingProvider(org.openhab.binding.openpaths.OpenPathsBindingProvider)

Example 15 with DecimalType

use of org.openhab.core.library.types.DecimalType in project openhab1-addons by openhab.

the class OnkyoBinding method convertDeviceValueToOpenHabState.

/**
     * Convert receiver value to OpenHAB state.
     *
     * @param itemType
     * @param data
     *
     * @return
     */
private State convertDeviceValueToOpenHabState(Class<? extends Item> itemType, String data) {
    State state = UnDefType.UNDEF;
    try {
        int index;
        String s;
        if (itemType == SwitchItem.class) {
            index = Integer.parseInt(data.substring(3, 5), 16);
            state = index == 0 ? OnOffType.OFF : OnOffType.ON;
        } else if (itemType == NumberItem.class) {
            index = Integer.parseInt(data.substring(3, 5), 16);
            state = new DecimalType(index);
        } else if (itemType == DimmerItem.class) {
            index = Integer.parseInt(data.substring(3, 5), 16);
            state = new PercentType(index);
        } else if (itemType == RollershutterItem.class) {
            index = Integer.parseInt(data.substring(3, 5), 16);
            state = new PercentType(index);
        } else if (itemType == StringItem.class) {
            s = data.substring(3, data.length());
            state = new StringType(s);
        }
    } catch (Exception e) {
        logger.debug("Cannot convert value '{}' to data type {}", data, itemType);
    }
    return state;
}
Also used : NumberItem(org.openhab.core.library.items.NumberItem) StringType(org.openhab.core.library.types.StringType) State(org.openhab.core.types.State) RollershutterItem(org.openhab.core.library.items.RollershutterItem) DecimalType(org.openhab.core.library.types.DecimalType) PercentType(org.openhab.core.library.types.PercentType) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Aggregations

DecimalType (org.openhab.core.library.types.DecimalType)222 Test (org.junit.Test)70 StringType (org.openhab.core.library.types.StringType)69 OnOffType (org.openhab.core.library.types.OnOffType)63 PercentType (org.openhab.core.library.types.PercentType)43 State (org.openhab.core.types.State)40 Type (org.openhab.core.types.Type)39 NumberItem (org.openhab.core.library.items.NumberItem)38 SHCMessage (org.openhab.binding.smarthomatic.internal.SHCMessage)37 DateTimeType (org.openhab.core.library.types.DateTimeType)29 BigDecimal (java.math.BigDecimal)23 Calendar (java.util.Calendar)23 HSBType (org.openhab.core.library.types.HSBType)20 SwitchItem (org.openhab.core.library.items.SwitchItem)18 IOException (java.io.IOException)16 StringItem (org.openhab.core.library.items.StringItem)16 ConfigurationException (org.osgi.service.cm.ConfigurationException)16 RollershutterItem (org.openhab.core.library.items.RollershutterItem)15 ContactItem (org.openhab.core.library.items.ContactItem)14 DimmerItem (org.openhab.core.library.items.DimmerItem)14