Search in sources :

Example 46 with DateTimeType

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

the class MysqlPersistenceService method query.

@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    if (!initialized) {
        logger.debug("Query aborted on item {} - mySQL not initialised!", filter.getItemName());
        return Collections.emptyList();
    }
    if (!isConnected()) {
        connectToDatabase();
    }
    if (!isConnected()) {
        logger.debug("Query aborted on item {} - mySQL not connected!", filter.getItemName());
        return Collections.emptyList();
    }
    SimpleDateFormat mysqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // Get the item name from the filter
    // Also get the Item object so we can determine the type
    Item item = null;
    String itemName = filter.getItemName();
    logger.debug("mySQL query: item is {}", itemName);
    try {
        if (itemRegistry != null) {
            item = itemRegistry.getItem(itemName);
        }
    } catch (ItemNotFoundException e1) {
        logger.error("Unable to get item type for {}", itemName);
        // Set type to null - data will be returned as StringType
        item = null;
    }
    if (item instanceof GroupItem) {
        // For Group Items is BaseItem needed to get correct Type of Value.
        item = GroupItem.class.cast(item).getBaseItem();
    }
    String table = sqlTables.get(itemName);
    if (table == null) {
        logger.error("mySQL: Unable to find table for query '{}'.", itemName);
        return Collections.emptyList();
    }
    String filterString = new String();
    if (filter.getBeginDate() != null) {
        if (filterString.isEmpty()) {
            filterString += " WHERE";
        } else {
            filterString += " AND";
        }
        filterString += " TIME>'" + mysqlDateFormat.format(filter.getBeginDate()) + "'";
    }
    if (filter.getEndDate() != null) {
        if (filterString.isEmpty()) {
            filterString += " WHERE";
        } else {
            filterString += " AND";
        }
        filterString += " TIME<'" + mysqlDateFormat.format(filter.getEndDate().getTime()) + "'";
    }
    if (filter.getOrdering() == Ordering.ASCENDING) {
        filterString += " ORDER BY Time ASC";
    } else {
        filterString += " ORDER BY Time DESC";
    }
    if (filter.getPageSize() != 0x7fffffff) {
        filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize();
    }
    try {
        long timerStart = System.currentTimeMillis();
        // Retrieve the table array
        Statement st = connection.createStatement();
        String queryString = new String();
        queryString = "SELECT Time, Value FROM " + table;
        if (!filterString.isEmpty()) {
            queryString += filterString;
        }
        logger.debug("mySQL: query:" + queryString);
        // Turn use of the cursor on.
        st.setFetchSize(50);
        ResultSet rs = st.executeQuery(queryString);
        long count = 0;
        List<HistoricItem> items = new ArrayList<HistoricItem>();
        State state;
        while (rs.next()) {
            count++;
            if (item instanceof NumberItem) {
                state = new DecimalType(rs.getDouble(2));
            } else if (item instanceof ColorItem) {
                state = new HSBType(rs.getString(2));
            } else if (item instanceof DimmerItem) {
                state = new PercentType(rs.getInt(2));
            } else if (item instanceof SwitchItem) {
                state = OnOffType.valueOf(rs.getString(2));
            } else if (item instanceof ContactItem) {
                state = OpenClosedType.valueOf(rs.getString(2));
            } else if (item instanceof RollershutterItem) {
                state = new PercentType(rs.getInt(2));
            } else if (item instanceof DateTimeItem) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(rs.getTimestamp(2).getTime());
                state = new DateTimeType(calendar);
            } else {
                state = new StringType(rs.getString(2));
            }
            MysqlItem mysqlItem = new MysqlItem(itemName, state, rs.getTimestamp(1));
            items.add(mysqlItem);
        }
        rs.close();
        st.close();
        long timerStop = System.currentTimeMillis();
        logger.debug("mySQL: query returned {} rows in {}ms", count, timerStop - timerStart);
        // Success
        errCnt = 0;
        return items;
    } catch (SQLException e) {
        errCnt++;
        logger.error("mySQL: Error running querying : ", e.getMessage());
    }
    return null;
}
Also used : StringType(org.openhab.core.library.types.StringType) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ColorItem(org.openhab.core.library.items.ColorItem) DateTimeItem(org.openhab.core.library.items.DateTimeItem) DimmerItem(org.openhab.core.library.items.DimmerItem) SwitchItem(org.openhab.core.library.items.SwitchItem) ColorItem(org.openhab.core.library.items.ColorItem) DateTimeItem(org.openhab.core.library.items.DateTimeItem) HistoricItem(org.openhab.core.persistence.HistoricItem) NumberItem(org.openhab.core.library.items.NumberItem) GroupItem(org.openhab.core.items.GroupItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) Item(org.openhab.core.items.Item) ContactItem(org.openhab.core.library.items.ContactItem) ResultSet(java.sql.ResultSet) DimmerItem(org.openhab.core.library.items.DimmerItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) GroupItem(org.openhab.core.items.GroupItem) HistoricItem(org.openhab.core.persistence.HistoricItem) HSBType(org.openhab.core.library.types.HSBType) SwitchItem(org.openhab.core.library.items.SwitchItem) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ContactItem(org.openhab.core.library.items.ContactItem) Calendar(java.util.Calendar) PercentType(org.openhab.core.library.types.PercentType) NumberItem(org.openhab.core.library.items.NumberItem) DateTimeType(org.openhab.core.library.types.DateTimeType) State(org.openhab.core.types.State) DecimalType(org.openhab.core.library.types.DecimalType) SimpleDateFormat(java.text.SimpleDateFormat) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 47 with DateTimeType

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

the class CosemDate method parse.

/**
     * Parses a String value to an openHAB DateTimeType
     * <p>
     * The input string must be in the format yyMMddHHmmssX
     * <p>
     * Based on the DSMR specification X is:
     * <p>
     * <ul>
     * <li>''. Valid for DSMR v3 specification
     * <li>'S'. Specifies a summer time (DST = 1) datetime
     * <li>'W'. Specifies a winter time (DST = 0) datetime
     * </ul>
     *
     * @param cosemValue
     *            the value to parse
     * @return {@link DateTimeType} on success
     * @throws ParseException
     *             if parsing failed
     */
@Override
protected DateTimeType parse(String cosemValue) throws ParseException {
    for (CosemDateFormat cosemDateFormat : CosemDateFormat.values()) {
        logger.debug("Trying pattern: {}", cosemDateFormat.pattern);
        Matcher m = cosemDateFormat.pattern.matcher(cosemValue);
        if (m.matches()) {
            logger.debug("{} matches pattern: {}", cosemValue, cosemDateFormat.pattern);
            Date date = cosemDateFormat.formatter.parse(m.group(1));
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            return new DateTimeType(c);
        }
        logger.debug("{} does not match pattern: {}", cosemValue, cosemDateFormat.pattern);
    }
    throw new ParseException("value: " + cosemValue + " is not a known CosemDate string", 0);
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) Matcher(java.util.regex.Matcher) Calendar(java.util.Calendar) ParseException(java.text.ParseException) Date(java.util.Date)

Example 48 with DateTimeType

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

the class PlanetPublisher method publishValue.

/**
     * Publishes the item with the value, if the item is a OnOffType and the
     * value is a calendar, a job is scheduled.
     */
private void publishValue(Item item, Object value, AstroBindingConfig bindingConfig) {
    if (value == null) {
        context.getEventPublisher().postUpdate(item.getName(), UnDefType.UNDEF);
    } else if (value instanceof Calendar) {
        Calendar calendar = (Calendar) value;
        if (bindingConfig.getOffset() != 0) {
            calendar = (Calendar) calendar.clone();
            calendar.add(Calendar.MINUTE, bindingConfig.getOffset());
        }
        if (item.getAcceptedDataTypes().contains(DateTimeType.class)) {
            context.getEventPublisher().postUpdate(item.getName(), new DateTimeType(calendar));
        } else if (item.getAcceptedCommandTypes().contains(OnOffType.class)) {
            context.getJobScheduler().scheduleItem(calendar, item.getName());
        } else {
            logger.warn("Unsupported type for item {}, only DateTimeType and OnOffType supported!", item.getName());
        }
    } else if (value instanceof Number) {
        if (item.getAcceptedDataTypes().contains(DecimalType.class)) {
            BigDecimal decimalValue = new BigDecimal(value.toString()).setScale(2, RoundingMode.HALF_UP);
            context.getEventPublisher().postUpdate(item.getName(), new DecimalType(decimalValue));
        } else if (value instanceof Long && item.getAcceptedDataTypes().contains(StringType.class) && "duration".equals(bindingConfig.getProperty())) {
            // special case, transforming duration to minute:second string
            context.getEventPublisher().postUpdate(item.getName(), new StringType(durationToString((Long) value)));
        } else {
            logger.warn("Unsupported type for item {}, only DecimalType supported!", item.getName());
        }
    } else if (value instanceof String || value instanceof Enum) {
        if (item.getAcceptedDataTypes().contains(StringType.class)) {
            if (value instanceof Enum) {
                String enumValue = WordUtils.capitalizeFully(StringUtils.replace(value.toString(), "_", " "));
                context.getEventPublisher().postUpdate(item.getName(), new StringType(enumValue));
            } else {
                context.getEventPublisher().postUpdate(item.getName(), new StringType(value.toString()));
            }
        } else {
            logger.warn("Unsupported type for item {}, only String supported!", item.getName());
        }
    } else {
        logger.warn("Unsupported value type {}", value.getClass().getSimpleName());
    }
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) StringType(org.openhab.core.library.types.StringType) Calendar(java.util.Calendar) DecimalType(org.openhab.core.library.types.DecimalType) BigDecimal(java.math.BigDecimal)

Example 49 with DateTimeType

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

the class FreeboxBinding method setDateTimeValue.

private void setDateTimeValue(Item item, long value) {
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(value * 1000);
    eventPublisher.postUpdate(item.getName(), new DateTimeType(c));
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) Calendar(java.util.Calendar)

Aggregations

DateTimeType (org.openhab.core.library.types.DateTimeType)49 Calendar (java.util.Calendar)37 DecimalType (org.openhab.core.library.types.DecimalType)30 StringType (org.openhab.core.library.types.StringType)29 State (org.openhab.core.types.State)16 DateTimeItem (org.openhab.core.library.items.DateTimeItem)12 PercentType (org.openhab.core.library.types.PercentType)12 NumberItem (org.openhab.core.library.items.NumberItem)11 BigDecimal (java.math.BigDecimal)10 OnOffType (org.openhab.core.library.types.OnOffType)9 ContactItem (org.openhab.core.library.items.ContactItem)8 DimmerItem (org.openhab.core.library.items.DimmerItem)8 StringItem (org.openhab.core.library.items.StringItem)8 HSBType (org.openhab.core.library.types.HSBType)8 Test (org.junit.Test)7 SwitchItem (org.openhab.core.library.items.SwitchItem)7 Date (java.util.Date)6 ColorItem (org.openhab.core.library.items.ColorItem)6 RollershutterItem (org.openhab.core.library.items.RollershutterItem)6 ArrayList (java.util.ArrayList)5