Search in sources :

Example 66 with DecimalType

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

the class KNXCoreTypeMapper method toDPTValue.

/*
     * (non-Javadoc)
     *
     * @see org.openhab.binding.knx.config.KNXTypeMapper#toDPTValue(org.openhab.core.types.Type, java.lang.String)
     */
@Override
public String toDPTValue(Type type, String dptID) {
    DPT dpt;
    int mainNumber = getMainNumber(dptID);
    if (mainNumber == -1) {
        logger.error("toDPTValue couldn't identify mainnumber in dptID: {}", dptID);
        return null;
    }
    try {
        DPTXlator translator = TranslatorTypes.createTranslator(mainNumber, dptID);
        dpt = translator.getType();
    } catch (KNXException e) {
        e.printStackTrace();
        return null;
    }
    // check for HSBType first, because it extends PercentType as well
    if (type instanceof HSBType) {
        Color color = ((HSBType) type).toColor();
        return "r:" + Integer.toString(color.getRed()) + " g:" + Integer.toString(color.getGreen()) + " b:" + Integer.toString(color.getBlue());
    } else if (type instanceof OnOffType) {
        return type.equals(OnOffType.OFF) ? dpt.getLowerValue() : dpt.getUpperValue();
    } else if (type instanceof UpDownType) {
        return type.equals(UpDownType.UP) ? dpt.getLowerValue() : dpt.getUpperValue();
    } else if (type instanceof IncreaseDecreaseType) {
        DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();
        return type.equals(IncreaseDecreaseType.DECREASE) ? valueDPT.getLowerValue() + " 5" : valueDPT.getUpperValue() + " 5";
    } else if (type instanceof OpenClosedType) {
        return type.equals(OpenClosedType.CLOSED) ? dpt.getLowerValue() : dpt.getUpperValue();
    } else if (type instanceof StopMoveType) {
        return type.equals(StopMoveType.STOP) ? dpt.getLowerValue() : dpt.getUpperValue();
    } else if (type instanceof PercentType) {
        return type.toString();
    } else if (type instanceof DecimalType) {
        switch(mainNumber) {
            case 2:
                DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();
                switch(((DecimalType) type).intValue()) {
                    case 0:
                        return "0 " + valueDPT.getLowerValue();
                    case 1:
                        return "0 " + valueDPT.getUpperValue();
                    case 2:
                        return "1 " + valueDPT.getLowerValue();
                    default:
                        return "1 " + valueDPT.getUpperValue();
                }
            case 18:
                int intVal = ((DecimalType) type).intValue();
                if (intVal > 63) {
                    return "learn " + (intVal - 0x80);
                } else {
                    return "activate " + intVal;
                }
            default:
                return type.toString();
        }
    } else if (type instanceof StringType) {
        return type.toString();
    } else if (type instanceof DateTimeType) {
        return formatDateTime((DateTimeType) type, dptID);
    }
    logger.debug("toDPTValue: Couldn't get value for {} dpt id {} (no mapping).", type, dptID);
    return null;
}
Also used : KNXException(tuwien.auto.calimero.exception.KNXException) StringType(org.openhab.core.library.types.StringType) Color(java.awt.Color) DPT(tuwien.auto.calimero.dptxlator.DPT) UpDownType(org.openhab.core.library.types.UpDownType) PercentType(org.openhab.core.library.types.PercentType) Datapoint(tuwien.auto.calimero.datapoint.Datapoint) StopMoveType(org.openhab.core.library.types.StopMoveType) DateTimeType(org.openhab.core.library.types.DateTimeType) DPTXlator(tuwien.auto.calimero.dptxlator.DPTXlator) OnOffType(org.openhab.core.library.types.OnOffType) OpenClosedType(org.openhab.core.library.types.OpenClosedType) DPTXlator3BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled) DecimalType(org.openhab.core.library.types.DecimalType) IncreaseDecreaseType(org.openhab.core.library.types.IncreaseDecreaseType) DPTXlator1BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled) HSBType(org.openhab.core.library.types.HSBType)

Example 67 with DecimalType

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

the class k8055Binding method execute.

/**
     * @{inheritDoc
     */
@Override
protected void execute() {
    logger.debug("execute() method is called!");
    try {
        if (!connect()) {
            logger.error("Not connected to hardware. Skipping attempt to read inputs.");
            return;
        }
        // Read all of the digital inputs in one go
        long inputs = sysLibrary.ReadAllDigital();
        if (inputs < 0) {
            throw new Exception("Failed to read digital inputs from hardware");
        }
        for (k8055BindingProvider provider : this.providers) {
            for (String itemName : provider.getItemNames()) {
                k8055BindingConfig config = provider.getItemConfig(itemName);
                if (IOType.DIGITAL_IN.equals(config.ioType)) {
                    boolean newstate = (inputs & (1 << (config.ioNumber - 1))) != 0;
                    boolean oldstate = (lastDigitalInputs & (1 << (config.ioNumber - 1))) != 0;
                    // hardware)
                    if (lastDigitalInputs < 0 || newstate != oldstate) {
                        if (newstate) {
                            eventPublisher.postUpdate(itemName, OpenClosedType.CLOSED);
                        } else {
                            eventPublisher.postUpdate(itemName, OpenClosedType.OPEN);
                        }
                    }
                } else if (IOType.ANALOG_IN.equals(config.ioType)) {
                    int state = sysLibrary.ReadAnalogChannel(config.ioNumber);
                    if (inputs < 0) {
                        throw new Exception("Failed to read analog channel " + config.ioNumber + " from hardware");
                    }
                    eventPublisher.postUpdate(itemName, new DecimalType(state));
                }
            }
        }
        lastDigitalInputs = inputs;
    } catch (Exception e) {
        // Connection failure
        logger.error("Failed to read from hardware ", e);
        connected = false;
        sysLibrary.CloseDevice();
    }
}
Also used : org.openhab.binding.k8055.internal.k8055GenericBindingProvider.k8055BindingConfig(org.openhab.binding.k8055.internal.k8055GenericBindingProvider.k8055BindingConfig) DecimalType(org.openhab.core.library.types.DecimalType) org.openhab.binding.k8055.k8055BindingProvider(org.openhab.binding.k8055.k8055BindingProvider) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 68 with DecimalType

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

the class KM200Comm method sendProvidersState.

/**
     * This function sets the state of a service on the device
     *
     */
public byte[] sendProvidersState(KM200BindingProvider provider, String item, Command command) {
    synchronized (device) {
        String type = null;
        String dataToSend = null;
        KM200CommObject object = null;
        Class<? extends Item> itemType = provider.getItemType(item);
        String service = checkParameterReplacement(provider, item);
        logger.debug("Prepare item for send: {} type: {} item: {}", service, type, itemType.getName());
        if (device.blacklistMap.contains(service)) {
            logger.debug("Service on blacklist: {}", service);
            return null;
        }
        if (device.serviceMap.containsKey(service)) {
            if (device.serviceMap.get(service).getWriteable() == 0) {
                logger.error("Service is listed as read-only: {}", service);
                return null;
            }
            object = device.serviceMap.get(service);
            type = object.getServiceType();
        } else {
            logger.error("Service is not in the determined device service list: {}", service);
            return null;
        }
        /* The service is availible, set now the values depeding on the item and binding type */
        logger.debug("state of: {} type: {}", command, type);
        /* Binding is a NumberItem */
        if (itemType.isAssignableFrom(NumberItem.class)) {
            BigDecimal bdVal = ((DecimalType) command).toBigDecimal();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked") List<BigDecimal> valParas = (List<BigDecimal>) object.getValueParameter();
                BigDecimal minVal = valParas.get(0);
                BigDecimal maxVal = valParas.get(1);
                if (bdVal.compareTo(minVal) < 0) {
                    bdVal = minVal;
                }
                if (bdVal.compareTo(maxVal) > 0) {
                    bdVal = maxVal;
                }
            }
            if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", bdVal).toString();
            } else if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", bdVal.toString()).toString();
            } else if (type.equals("switchProgram") && object.getVirtual() == 1) {
                /* A switchProgram as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else if (type.equals("errorList") && object.getVirtual() == 1) {
                /* A errorList as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for numberItem: {}", type);
            }
        /* Binding is a StringItem */
        } else if (itemType.isAssignableFrom(StringItem.class)) {
            String val = ((StringType) command).toString();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked") List<String> valParas = (List<String>) object.getValueParameter();
                if (!valParas.contains(val)) {
                    logger.warn("Parameter is not in the service parameterlist: {}", val);
                    return null;
                }
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", Float.parseFloat(val)).toString();
            } else if (type.equals("switchProgram")) {
                if (object.getVirtual() == 1) {
                    dataToSend = sendVirtualState(object, itemType, service, command);
                } else {
                    /* The JSONArray of switch items can be sended directly */
                    try {
                        /* Check whether ths input string is a valid JSONArray */
                        JSONArray userArray = new JSONArray(val);
                        dataToSend = userArray.toString();
                    } catch (Exception e) {
                        logger.warn("The input for the switchProgram is not a valid JSONArray : {}", e.getMessage());
                        return null;
                    }
                }
            } else {
                logger.warn("Not supported type for stringItem: {}", type);
            }
        /* Binding is a DateTimeItem */
        } else if (itemType.isAssignableFrom(DateTimeItem.class)) {
            String val = ((DateTimeType) command).toString();
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("switchProgram")) {
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for dateTimeItem: {}", type);
            }
        /* Binding is a SwitchItem */
        } else if (itemType.isAssignableFrom(SwitchItem.class)) {
            String val = null;
            if (provider.getParameter(item).containsKey("on")) {
                if (command == OnOffType.OFF) {
                    val = provider.getParameter(item).get("off");
                } else if (command == OnOffType.ON) {
                    val = provider.getParameter(item).get("on");
                }
            } else {
                logger.warn("Switch-Item only on configured on/off string values {}", command);
                return null;
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else {
                logger.warn("Not supported type for SwitchItem:{}", type);
            }
        } else {
            logger.warn("Bindingtype not supported: {}", itemType.getClass());
            return null;
        }
        /* If some data is availible then we have to send it to device */
        if (dataToSend != null) {
            /* base64 + encoding */
            logger.debug("Encoding: {}", dataToSend);
            byte[] encData = encodeMessage(dataToSend);
            if (encData == null) {
                logger.error("Couldn't encrypt data");
                return null;
            }
            return encData;
        } else {
            return null;
        }
    }
}
Also used : JSONArray(org.json.JSONArray) StringItem(org.openhab.core.library.items.StringItem) BigDecimal(java.math.BigDecimal) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DateTimeType(org.openhab.core.library.types.DateTimeType) JSONObject(org.json.JSONObject) DecimalType(org.openhab.core.library.types.DecimalType) ArrayList(java.util.ArrayList) List(java.util.List) SwitchItem(org.openhab.core.library.items.SwitchItem)

Example 69 with DecimalType

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

the class IRtransBinding method internalReceiveChanneledCommand.

/**
     * {@inheritDoc}
     */
@Override
protected boolean internalReceiveChanneledCommand(String itemName, Command command, Channel sChannel, String commandAsString) {
    IRtransBindingProvider provider = findFirstMatchingBindingProvider(itemName);
    String remoteName = null;
    String irCommandName = null;
    if (command != null && provider != null) {
        if (command instanceof DecimalType) {
            remoteName = StringUtils.substringBefore(commandAsString, ",");
            irCommandName = StringUtils.substringAfter(commandAsString, ",");
            IrCommand firstCommand = new IrCommand();
            firstCommand.remote = remoteName;
            firstCommand.command = irCommandName;
            IrCommand secondCommand = new IrCommand();
            secondCommand.remote = provider.getRemote(itemName, command);
            secondCommand.command = provider.getIrCommand(itemName, command);
            if (!firstCommand.matches(secondCommand)) {
                remoteName = null;
                irCommandName = null;
            }
        } else {
            remoteName = provider.getRemote(itemName, command);
            irCommandName = provider.getIrCommand(itemName, command);
        }
    }
    if (remoteName != null && irCommandName != null) {
        Leds led = provider.getLed(itemName, command);
        IrCommand theCommand = new IrCommand();
        theCommand.remote = remoteName;
        theCommand.command = irCommandName;
        // construct the string we need to send to the IRtrans device
        String output = packIRDBCommand(led, theCommand);
        ByteBuffer outputBuffer = ByteBuffer.allocate(output.getBytes().length);
        ByteBuffer response = null;
        try {
            outputBuffer.put(output.getBytes("ASCII"));
            response = writeBuffer(outputBuffer, sChannel, true, timeOut);
        } catch (UnsupportedEncodingException e) {
            logger.error("An exception occurred while encoding an infrared command: {}", e.getMessage());
        }
        if (response != null) {
            String message = stripByteCount(response);
            if (message != null) {
                if (message.contains("RESULT OK")) {
                    List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName, command);
                    State newState = createStateFromString(stateTypeList, commandAsString);
                    if (newState != null) {
                        eventPublisher.postUpdate(itemName, newState);
                    } else {
                        logger.warn("Can not parse " + commandAsString + " to match command {} on item {}  ", command, itemName);
                    }
                } else {
                    logger.warn("Received an unexpected response {}", StringUtils.substringAfter(message, "RESULT "));
                }
            }
        } else {
            logger.warn("Did not receive an answer from the IRtrans device - Parsing is skipped");
        }
    } else {
        logger.warn("Invalid command {} for Item {} - Transmission is skipped", commandAsString, itemName);
    }
    // not deal with that anymore.
    return false;
}
Also used : State(org.openhab.core.types.State) DecimalType(org.openhab.core.library.types.DecimalType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IRtransBindingProvider(org.openhab.binding.irtrans.IRtransBindingProvider) ByteBuffer(java.nio.ByteBuffer)

Example 70 with DecimalType

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

the class IRtransBinding method parseDecodedCommand.

protected void parseDecodedCommand(String itemName, IrCommand theCommand, Command ohCommand) {
    if (theCommand != null) {
        // traverse the providers, for each provider, check each binding if it matches theCommand
        for (IRtransBindingProvider provider : providers) {
            if (provider.providesBindingFor(itemName)) {
                List<org.openhab.core.types.Command> commands = provider.getAllCommands(itemName);
                // first check if commands are defined, and that they have the correct DirectionType
                Iterator<org.openhab.core.types.Command> listIterator = commands.listIterator();
                while (listIterator.hasNext()) {
                    org.openhab.core.types.Command aCommand = listIterator.next();
                    IrCommand providerCommand = new IrCommand();
                    providerCommand.remote = provider.getRemote(itemName, aCommand);
                    providerCommand.command = provider.getIrCommand(itemName, aCommand);
                    if (aCommand == ohCommand) {
                        if (providerCommand.matches(theCommand)) {
                            List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName, aCommand);
                            State newState = null;
                            if (aCommand instanceof DecimalType) {
                                newState = createStateFromString(stateTypeList, theCommand.remote + "," + theCommand.command);
                            } else {
                                newState = createStateFromString(stateTypeList, aCommand.toString());
                            }
                            if (newState != null) {
                                eventPublisher.postUpdate(itemName, newState);
                            } else {
                                logger.warn("Can not create an Item State to match command {} on item {}  ", aCommand, itemName);
                            }
                        } else {
                            logger.info("The IRtrans command '{},{}' does not match the command '{}' of the binding configuration for item '{}'", new Object[] { theCommand.remote, theCommand.command, ohCommand, itemName });
                        }
                    }
                }
            }
        }
    }
}
Also used : Command(org.openhab.core.types.Command) IRtransBindingProvider(org.openhab.binding.irtrans.IRtransBindingProvider) Command(org.openhab.core.types.Command) State(org.openhab.core.types.State) DecimalType(org.openhab.core.library.types.DecimalType)

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