Search in sources :

Example 1 with KNXException

use of tuwien.auto.calimero.exception.KNXException in project openhab1-addons by openhab.

the class KNXCoreTypeMapper method toType.

/*
     * (non-Javadoc)
     *
     * @see org.openhab.binding.knx.config.KNXTypeMapper#toType(tuwien.auto.calimero.datapoint.Datapoint, byte[])
     */
@Override
public Type toType(Datapoint datapoint, byte[] data) {
    try {
        DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
        translator.setData(data);
        String value = translator.getValue();
        String id = translator.getType().getID();
        logger.trace("toType datapoint DPT = " + datapoint.getDPT());
        int mainNumber = getMainNumber(id);
        if (mainNumber == -1) {
            logger.debug("toType: couldn't identify mainnumber in dptID: {}.", id);
            return null;
        }
        int subNumber = getSubNumber(id);
        if (subNumber == -1) {
            logger.debug("toType: couldn't identify sub number in dptID: {}.", id);
            return null;
        }
        /*
             * Following code section deals with specific mapping of values from KNX to openHAB types were the String
             * received from the DPTXlator is not sufficient to set the openHAB type or has bugs
             */
        switch(mainNumber) {
            case 1:
                DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
                switch(subNumber) {
                    case 8:
                        return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
                    case 9:
                        return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                    case 10:
                        return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
                    case 19:
                        return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                    case 22:
                        return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
                    default:
                        return translatorBoolean.getValueBoolean() ? OnOffType.ON : OnOffType.OFF;
                }
            case 2:
                DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
                int decValue = (translator1BitControlled.getControlBit() ? 2 : 0) + (translator1BitControlled.getValueBit() ? 1 : 0);
                return new DecimalType(decValue);
            case 3:
                DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
                if (translator3BitControlled.getStepCode() == 0) {
                    /*
                         * there is no STOP for a IncreaseDecreaseType, so we are just using an INCREASE.
                         * It is up to the binding to recognize that a start/stop-dimming is in progress and
                         * stop the dimming accordingly.
                         */
                    logger.debug("toType: KNX DPT_Control_Dimming: break received.");
                    return IncreaseDecreaseType.INCREASE;
                }
                switch(subNumber) {
                    case 7:
                        return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE : IncreaseDecreaseType.DECREASE;
                    case 8:
                        return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
                }
            case 14:
                /*
                     * FIXME: Workaround for a bug in Calimero / Openhab DPTXlator4ByteFloat.makeString(): is using a
                     * locale when
                     * translating a Float to String. It could happen the a ',' is used as separator, such as
                     * 3,14159E20.
                     * Openhab's DecimalType expects this to be in US format and expects '.': 3.14159E20.
                     * There is no issue with DPTXlator2ByteFloat since calimero is using a non-localized translation
                     * there.
                     */
                DPTXlator4ByteFloat translator4ByteFloat = (DPTXlator4ByteFloat) translator;
                Float f = translator4ByteFloat.getValueFloat();
                if (Math.abs(f) < 100000) {
                    value = String.valueOf(f);
                } else {
                    NumberFormat dcf = NumberFormat.getInstance(Locale.US);
                    if (dcf instanceof DecimalFormat) {
                        ((DecimalFormat) dcf).applyPattern("0.#####E0");
                    }
                    value = dcf.format(f);
                }
                break;
            case 18:
                DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
                int decimalValue = translatorSceneControl.getSceneNumber();
                if (value.startsWith("learn")) {
                    decimalValue += 0x80;
                }
                value = String.valueOf(decimalValue);
                break;
            case 19:
                DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
                if (translatorDateTime.isFaultyClock()) {
                    // Not supported: faulty clock
                    logger.debug("toType: KNX clock msg ignored: clock faulty bit set, which is not supported");
                    return null;
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
                    // Not supported: "/1/1" (month and day without year)
                    logger.debug("toType: KNX clock msg ignored: no year, but day and month, which is not supported");
                    return null;
                } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
                    // Not supported: "1900" (year without month and day)
                    logger.debug("toType: KNX clock msg ignored: no day and month, but year, which is not supported");
                    return null;
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE) && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Not supported: No year, no date and no time
                    logger.debug("toType: KNX clock msg ignored: no day and month or year, which is not supported");
                    return null;
                }
                Calendar cal = Calendar.getInstance();
                if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Pure date format, no time information
                    cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Pure time format, no date information
                    cal.clear();
                    cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
                    cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
                    cal.set(Calendar.SECOND, translatorDateTime.getSecond());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Date format and time information
                    cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                }
                break;
        }
        Class<? extends Type> typeClass = toTypeClass(id);
        if (typeClass == null) {
            return null;
        }
        if (typeClass.equals(PercentType.class)) {
            return PercentType.valueOf(value.split(" ")[0]);
        }
        if (typeClass.equals(DecimalType.class)) {
            return DecimalType.valueOf(value.split(" ")[0]);
        }
        if (typeClass.equals(StringType.class)) {
            return StringType.valueOf(value);
        }
        if (typeClass.equals(DateTimeType.class)) {
            String date = formatDateTime(value, datapoint.getDPT());
            if ((date == null) || (date.isEmpty())) {
                logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);
                return null;
            } else {
                return DateTimeType.valueOf(date);
            }
        }
        if (typeClass.equals(HSBType.class)) {
            // value has format of "r:<red value> g:<green value> b:<blue value>"
            int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);
            int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);
            int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);
            Color color = new Color(r, g, b);
            return new HSBType(color);
        }
    } catch (KNXFormatException kfe) {
        logger.info("Translator couldn't parse data for datapoint type '{}' (KNXFormatException).", datapoint.getDPT());
    } catch (KNXIllegalArgumentException kiae) {
        logger.info("Translator couldn't parse data for datapoint type '{}' (KNXIllegalArgumentException).", datapoint.getDPT());
    } catch (KNXException e) {
        logger.warn("Failed creating a translator for datapoint type '{}'.", datapoint.getDPT(), e);
    }
    return null;
}
Also used : KNXException(tuwien.auto.calimero.exception.KNXException) DPTXlatorDateTime(tuwien.auto.calimero.dptxlator.DPTXlatorDateTime) KNXIllegalArgumentException(tuwien.auto.calimero.exception.KNXIllegalArgumentException) DecimalFormat(java.text.DecimalFormat) Calendar(java.util.Calendar) Color(java.awt.Color) DPTXlatorString(tuwien.auto.calimero.dptxlator.DPTXlatorString) Datapoint(tuwien.auto.calimero.datapoint.Datapoint) DPTXlatorBoolean(tuwien.auto.calimero.dptxlator.DPTXlatorBoolean) DPTXlator2ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat) DPTXlator4ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat) DPTXlatorSceneControl(tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl) DPTXlator(tuwien.auto.calimero.dptxlator.DPTXlator) DecimalType(org.openhab.core.library.types.DecimalType) DPTXlator3BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled) DPTXlator4ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat) KNXFormatException(tuwien.auto.calimero.exception.KNXFormatException) DPTXlator1BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled) SimpleDateFormat(java.text.SimpleDateFormat) HSBType(org.openhab.core.library.types.HSBType) NumberFormat(java.text.NumberFormat)

Example 2 with KNXException

use of tuwien.auto.calimero.exception.KNXException 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 3 with KNXException

use of tuwien.auto.calimero.exception.KNXException in project openhab1-addons by openhab.

the class KNXBinding method writeToKNX.

private void writeToKNX(String itemName, Type value) {
    Iterable<Datapoint> datapoints = getDatapoints(itemName, value.getClass());
    if (datapoints != null) {
        ProcessCommunicator pc = KNXConnection.getCommunicator();
        if (pc != null) {
            for (Datapoint datapoint : datapoints) {
                try {
                    pc.write(datapoint, toDPTValue(value, datapoint.getDPT()));
                    logger.debug("Wrote value '{}' to datapoint '{}'", value, datapoint);
                } catch (KNXException e) {
                    logger.warn("Value '{}' could not be sent to the KNX bus using datapoint '{}' - retrying one time: {}", new Object[] { value, datapoint, e.getMessage() });
                    try {
                        // do a second try, maybe the reconnection was successful
                        pc = KNXConnection.getCommunicator();
                        pc.write(datapoint, toDPTValue(value, datapoint.getDPT()));
                        logger.debug("Wrote value '{}' to datapoint '{}' on second try", value, datapoint);
                    } catch (KNXException e1) {
                        logger.error("Value '{}' could not be sent to the KNX bus using datapoint '{}' - giving up after second try: {}", new Object[] { value, datapoint, e1.getMessage() });
                    }
                }
            }
        }
    }
}
Also used : Datapoint(tuwien.auto.calimero.datapoint.Datapoint) KNXException(tuwien.auto.calimero.exception.KNXException) ProcessCommunicator(tuwien.auto.calimero.process.ProcessCommunicator)

Example 4 with KNXException

use of tuwien.auto.calimero.exception.KNXException in project openhab1-addons by openhab.

the class KNXBindingDatapointReaderTask method readFromKNXBus.

private void readFromKNXBus(Datapoint datapoint) throws InterruptedException {
    try {
        ProcessCommunicator pc = KNXConnection.getCommunicator();
        if (pc != null) {
            sLogger.debug("Autorefresh: Sending read request to KNX for item '{}' DPT '{}'", datapoint.getName(), datapoint.getDPT());
            pc.read(datapoint);
        } else {
            sLogger.debug("Autorefresh: Couldn't sent read request to KNX for item '{}'. Connection to KNX bus not (yet) established.", datapoint.getName());
        }
    } catch (KNXFormatException e) {
        sLogger.warn("Autorefresh: Cannot read value for item '{}' from KNX bus: {}: invalid format", datapoint.getName(), e.getMessage());
    } catch (KNXInvalidResponseException e) {
        sLogger.warn("Autorefresh: Cannot read value for item '{}' from KNX bus: {}: invalid response", datapoint.getName(), e.getMessage());
    } catch (KNXTimeoutException e) {
        sLogger.warn("Autorefresh: Cannot read value for item '{}' from KNX bus: {}: timeout", datapoint.getName(), e.getMessage());
        addToReadQueue(datapoint);
    } catch (KNXLinkClosedException e) {
        sLogger.warn("Autorefresh: Cannot read value for item '{}' from KNX bus: {}: link closed", datapoint.getName(), e.getMessage());
    } catch (KNXException e) {
        sLogger.warn("Autorefresh: Cannot read value for item '{}' from KNX bus: {}", datapoint.getName(), e.getMessage());
    } catch (KNXIllegalArgumentException e) {
        sLogger.warn("Autorefresh: Error sending KNX read request for '{}': {}", datapoint.getName(), e.getMessage());
    }
}
Also used : KNXInvalidResponseException(tuwien.auto.calimero.exception.KNXInvalidResponseException) KNXTimeoutException(tuwien.auto.calimero.exception.KNXTimeoutException) KNXException(tuwien.auto.calimero.exception.KNXException) KNXLinkClosedException(tuwien.auto.calimero.link.KNXLinkClosedException) KNXIllegalArgumentException(tuwien.auto.calimero.exception.KNXIllegalArgumentException) KNXFormatException(tuwien.auto.calimero.exception.KNXFormatException) ProcessCommunicator(tuwien.auto.calimero.process.ProcessCommunicator)

Example 5 with KNXException

use of tuwien.auto.calimero.exception.KNXException in project openhab1-addons by openhab.

the class KNXConnection method connect.

/**
     * Tries to connect either by IP or serial bus, depending on supplied config data.
     * 
     * @return true if connection was established, false otherwise
     */
public static synchronized boolean connect() {
    boolean successRetVal = false;
    sShutdown = false;
    try {
        if (StringUtils.isNotBlank(sIp)) {
            sLink = connectByIp(sIpConnectionType, sLocalIp, sIp, sPort);
        } else if (StringUtils.isNotBlank(sSerialPort)) {
            sLink = connectBySerial(sSerialPort);
        } else {
            sLogger.error("No IP address or serial port could be found in configuration!");
            return false;
        }
        NetworkLinkListener linkListener = new NetworkLinkListener() {

            @Override
            public void linkClosed(CloseEvent e) {
                if (!(CloseEvent.USER_REQUEST == e.getInitiator()) && !sShutdown) {
                    sLogger.warn("KNX link has been lost (reason: {} on object {})", e.getReason(), e.getSource().toString());
                    for (KNXConnectionListener listener : KNXConnection.sConnectionListeners) {
                        listener.connectionLost();
                    }
                    if (sAutoReconnectPeriod > 0) {
                        sLogger.info("KNX link will be retried in " + sAutoReconnectPeriod + " seconds");
                        final Timer timer = new Timer();
                        TimerTask timerTask = new ConnectTimerTask(timer);
                        timer.schedule(timerTask, sAutoReconnectPeriod * 1000, sAutoReconnectPeriod * 1000);
                    }
                }
            }

            @Override
            public void indication(FrameEvent e) {
            }

            @Override
            public void confirmation(FrameEvent e) {
            }
        };
        sLink.addLinkListener(linkListener);
        if (sPC != null) {
            sPC.removeProcessListener(sProcessCommunicationListener);
            sPC.detach();
        }
        sPC = new ProcessCommunicatorImpl(sLink);
        sPC.setResponseTimeout((int) sResponseTimeout / 1000);
        if (sProcessCommunicationListener != null) {
            sPC.addProcessListener(sProcessCommunicationListener);
        }
        if (sLogger.isInfoEnabled()) {
            if (sLink instanceof KNXNetworkLinkIP) {
                String ipConnectionTypeString = KNXConnection.sIpConnectionType == KNXNetworkLinkIP.ROUTING ? "ROUTER" : "TUNNEL";
                sLogger.info("Established connection to KNX bus on {} in mode {}.", sIp + ":" + sPort, ipConnectionTypeString);
            } else {
                sLogger.info("Established connection to KNX bus through FT1.2 on serial port {}.", sSerialPort);
            }
        }
        for (KNXConnectionListener listener : KNXConnection.sConnectionListeners) {
            listener.connectionEstablished();
        }
        successRetVal = true;
    } catch (KNXException e) {
        sLogger.error("Error connecting to KNX bus: {}", e.getMessage());
    } catch (UnknownHostException e) {
        sLogger.error("Error connecting to KNX bus (unknown host): {}", e.getMessage());
    } catch (InterruptedException e) {
        sLogger.error("Error connecting to KNX bus (interrupted): {}", e.getMessage());
    }
    return successRetVal;
}
Also used : KNXException(tuwien.auto.calimero.exception.KNXException) CloseEvent(tuwien.auto.calimero.CloseEvent) UnknownHostException(java.net.UnknownHostException) KNXNetworkLinkIP(tuwien.auto.calimero.link.KNXNetworkLinkIP) FrameEvent(tuwien.auto.calimero.FrameEvent) NetworkLinkListener(tuwien.auto.calimero.link.NetworkLinkListener) Timer(java.util.Timer) TimerTask(java.util.TimerTask) ProcessCommunicatorImpl(tuwien.auto.calimero.process.ProcessCommunicatorImpl)

Aggregations

KNXException (tuwien.auto.calimero.exception.KNXException)5 Datapoint (tuwien.auto.calimero.datapoint.Datapoint)3 Color (java.awt.Color)2 DecimalType (org.openhab.core.library.types.DecimalType)2 HSBType (org.openhab.core.library.types.HSBType)2 DPTXlator (tuwien.auto.calimero.dptxlator.DPTXlator)2 DPTXlator1BitControlled (tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled)2 DPTXlator3BitControlled (tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled)2 KNXFormatException (tuwien.auto.calimero.exception.KNXFormatException)2 KNXIllegalArgumentException (tuwien.auto.calimero.exception.KNXIllegalArgumentException)2 ProcessCommunicator (tuwien.auto.calimero.process.ProcessCommunicator)2 UnknownHostException (java.net.UnknownHostException)1 DecimalFormat (java.text.DecimalFormat)1 NumberFormat (java.text.NumberFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Calendar (java.util.Calendar)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 DateTimeType (org.openhab.core.library.types.DateTimeType)1 IncreaseDecreaseType (org.openhab.core.library.types.IncreaseDecreaseType)1