Search in sources :

Example 6 with RollershutterItem

use of org.openhab.core.library.items.RollershutterItem in project openhab1-addons by openhab.

the class MysqlPersistenceService method store.

/**
     * @{inheritDoc
     */
@Override
public void store(Item item, String alias) {
    // Don't log undefined/uninitialised data
    if (item.getState() instanceof UnDefType) {
        return;
    }
    // If we've not initialised the bundle, then return
    if (initialized == false) {
        return;
    }
    // Connect to mySQL server if we're not already connected
    if (!isConnected()) {
        connectToDatabase();
    }
    // If we still didn't manage to connect, then return!
    if (!isConnected()) {
        logger.warn("mySQL: No connection to database. Can not persist item '{}'! " + "Will retry connecting to database when error count:{} equals errReconnectThreshold:{}", item, errCnt, errReconnectThreshold);
        return;
    }
    // Get the table name for this item
    String tableName = getTable(item);
    if (tableName == null) {
        logger.error("Unable to store item '{}'.", item.getName());
        return;
    }
    // Do some type conversion to ensure we know the data type.
    // This is necessary for items that have multiple types and may return their
    // state in a format that's not preferred or compatible with the MySQL type.
    // eg. DimmerItem can return OnOffType (ON, OFF), or PercentType (0-100).
    // We need to make sure we cover the best type for serialisation.
    String value;
    if (item instanceof ColorItem) {
        value = item.getStateAs(HSBType.class).toString();
    } else if (item instanceof RollershutterItem) {
        value = item.getStateAs(PercentType.class).toString();
    } else {
        /*
             * !!ATTENTION!!
             * 
             * 1.
             * DimmerItem.getStateAs(PercentType.class).toString() always returns 0
             * RollershutterItem.getStateAs(PercentType.class).toString() works as expected
             * 
             * 2.
             * (item instanceof ColorItem) == (item instanceof DimmerItem) = true
             * Therefore for instance tests ColorItem always has to be tested before DimmerItem
             * 
             * !!ATTENTION!!
             */
        // All other items should return the best format by default
        value = item.getState().toString();
    }
    // Get current timestamp
    long timeNow = Calendar.getInstance().getTimeInMillis();
    Timestamp timestamp = new Timestamp(timeNow);
    String sqlCmd = null;
    PreparedStatement statement = null;
    try {
        if (localtime) {
            sqlCmd = new String("INSERT INTO " + tableName + " (TIME, VALUE) VALUES(?,?) ON DUPLICATE KEY UPDATE VALUE=?;");
            statement = connection.prepareStatement(sqlCmd);
            statement.setTimestamp(1, timestamp);
            statement.setString(2, value);
            statement.setString(3, value);
        } else {
            sqlCmd = new String("INSERT INTO " + tableName + " (TIME, VALUE) VALUES(NOW(),?) ON DUPLICATE KEY UPDATE VALUE=?;");
            statement = connection.prepareStatement(sqlCmd);
            statement.setString(1, value);
            statement.setString(2, value);
        }
        statement.executeUpdate();
        logger.debug("mySQL: Stored item '{}' as '{}'[{}] in SQL database at {}.", item.getName(), item.getState().toString(), value, timestamp.toString());
        logger.debug("mySQL: query: {}", sqlCmd);
        // Success
        errCnt = 0;
    } catch (Exception e) {
        errCnt++;
        logger.error("mySQL: Could not store item '{}' in database with " + "statement '{}': {}", item.getName(), sqlCmd, e.getMessage());
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception hidden) {
            }
        }
    }
}
Also used : UnDefType(org.openhab.core.types.UnDefType) RollershutterItem(org.openhab.core.library.items.RollershutterItem) ColorItem(org.openhab.core.library.items.ColorItem) PreparedStatement(java.sql.PreparedStatement) PercentType(org.openhab.core.library.types.PercentType) Timestamp(java.sql.Timestamp) SQLException(java.sql.SQLException) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 7 with RollershutterItem

use of org.openhab.core.library.items.RollershutterItem in project openhab1-addons by openhab.

the class InfluxDBPersistenceService method store.

/**
   * {@inheritDoc}
   */
@Override
public void store(Item item, String alias) {
    if (item.getState() instanceof UnDefType) {
        return;
    }
    if (!isProperlyConfigured) {
        logger.warn("Configuration for influxdb08 not yet loaded or broken.");
        return;
    }
    if (!isConnected()) {
        logger.warn("InfluxDB is not yet connected");
        return;
    }
    String realName = item.getName();
    String name = (alias != null) ? alias : realName;
    State state = null;
    if (item instanceof DimmerItem || item instanceof RollershutterItem) {
        state = item.getStateAs(PercentType.class);
    } else if (item instanceof ColorItem) {
        state = item.getStateAs(HSBType.class);
    } else {
        // All other items should return the best format by default
        state = item.getState();
    }
    Object value = stateToObject(state);
    logger.trace("storing {} in influxdb08 {}", name, value);
    // For now time is calculated by influxdb08, may be this should be configurable?
    Serie serie = new Serie.Builder(name).columns(VALUE_COLUMN_NAME).values(value).build();
    try {
        influxDB.write(dbName, TimeUnit.MILLISECONDS, serie);
    } catch (RuntimeException e) {
        logger.error("storing failed with exception for item: {}", name);
        handleDatabaseException(e);
    }
}
Also used : UnDefType(org.openhab.core.types.UnDefType) State(org.openhab.core.types.State) DimmerItem(org.openhab.core.library.items.DimmerItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) ColorItem(org.openhab.core.library.items.ColorItem) PercentType(org.openhab.core.library.types.PercentType) Serie(org.influxdb.dto.Serie)

Example 8 with RollershutterItem

use of org.openhab.core.library.items.RollershutterItem in project openhab1-addons by openhab.

the class RollershutterItemIntegrationTest method storeData.

@BeforeClass
public static void storeData() throws InterruptedException {
    RollershutterItem item = (RollershutterItem) items.get(name);
    item.setState(state1);
    beforeStore = new Date();
    Thread.sleep(10);
    service.store(item);
    afterStore1 = new Date();
    Thread.sleep(10);
    item.setState(state2);
    service.store(item);
    Thread.sleep(10);
    afterStore2 = new Date();
    logger.info("Created item between {} and {}", AbstractDynamoDBItem.DATEFORMATTER.format(beforeStore), AbstractDynamoDBItem.DATEFORMATTER.format(afterStore1));
}
Also used : RollershutterItem(org.openhab.core.library.items.RollershutterItem) Date(java.util.Date) BeforeClass(org.junit.BeforeClass)

Example 9 with RollershutterItem

use of org.openhab.core.library.items.RollershutterItem in project openhab1-addons by openhab.

the class AbstractDynamoDBItem method asHistoricItem.

/*
     * (non-Javadoc)
     *
     * @see org.openhab.persistence.dynamodb.internal.DynamoItem#asHistoricItem(org.openhab.core.items.Item)
     */
@Override
public HistoricItem asHistoricItem(final Item item) {
    final State[] state = new State[1];
    accept(new DynamoDBItemVisitor() {

        @Override
        public void visit(DynamoDBStringItem dynamoStringItem) {
            if (item instanceof ColorItem) {
                state[0] = new HSBType(dynamoStringItem.getState());
            } else if (item instanceof LocationItem) {
                state[0] = new PointType(dynamoStringItem.getState());
            } else if (item instanceof DateTimeItem) {
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                try {
                    cal.setTime(DATEFORMATTER.parse(dynamoStringItem.getState()));
                } catch (ParseException e) {
                    LOGGER.error("Failed to parse {} as date. Outputting UNDEF instead", dynamoStringItem.getState());
                    state[0] = UnDefType.UNDEF;
                }
                state[0] = new DateTimeType(cal);
            } else if (dynamoStringItem.getState().equals(UNDEFINED_PLACEHOLDER)) {
                state[0] = UnDefType.UNDEF;
            } else if (item instanceof CallItem) {
                String parts = dynamoStringItem.getState();
                String[] strings = parts.split("##");
                String dest = strings[0];
                String orig = strings[1];
                state[0] = new CallType(orig, dest);
            } else {
                state[0] = new StringType(dynamoStringItem.getState());
            }
        }

        @Override
        public void visit(DynamoDBBigDecimalItem dynamoBigDecimalItem) {
            if (item instanceof NumberItem) {
                state[0] = new DecimalType(dynamoBigDecimalItem.getState());
            } else if (item instanceof DimmerItem) {
                state[0] = new PercentType(dynamoBigDecimalItem.getState());
            } else if (item instanceof SwitchItem) {
                state[0] = dynamoBigDecimalItem.getState().compareTo(BigDecimal.ONE) == 0 ? OnOffType.ON : OnOffType.OFF;
            } else if (item instanceof ContactItem) {
                state[0] = dynamoBigDecimalItem.getState().compareTo(BigDecimal.ONE) == 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
            } else if (item instanceof RollershutterItem) {
                state[0] = new PercentType(dynamoBigDecimalItem.getState());
            } else {
                LOGGER.warn("Not sure how to convert big decimal item {} to type {}. Using StringType as fallback", dynamoBigDecimalItem.getName(), item.getClass());
                state[0] = new StringType(dynamoBigDecimalItem.getState().toString());
            }
        }
    });
    return new DynamoDBHistoricItem(getName(), state[0], getTime());
}
Also used : LocationItem(org.openhab.core.library.items.LocationItem) StringType(org.openhab.core.library.types.StringType) CallType(org.openhab.library.tel.types.CallType) ColorItem(org.openhab.core.library.items.ColorItem) DateTimeItem(org.openhab.core.library.items.DateTimeItem) DimmerItem(org.openhab.core.library.items.DimmerItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) HSBType(org.openhab.core.library.types.HSBType) SwitchItem(org.openhab.core.library.items.SwitchItem) Calendar(java.util.Calendar) ContactItem(org.openhab.core.library.items.ContactItem) 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) PointType(org.openhab.core.library.types.PointType) DecimalType(org.openhab.core.library.types.DecimalType) CallItem(org.openhab.library.tel.items.CallItem) ParseException(java.text.ParseException)

Example 10 with RollershutterItem

use of org.openhab.core.library.items.RollershutterItem in project openhab1-addons by openhab.

the class SappBinding method updateState.

/**
     * updates item repository for a single item
     */
private void updateState(String pnmasId, SappAddressType sappAddressType, int addressToUpdate, int newState, SappBindingProvider provider) {
    logger.debug("Updating {} {} with new value {}", sappAddressType, addressToUpdate, newState);
    for (String itemName : provider.getItemNames()) {
        try {
            Item item = itemRegistry.getItem(itemName);
            if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
                SappBindingConfigSwitchItem sappBindingConfigSwitchItem = (SappBindingConfigSwitchItem) provider.getBindingConfig(itemName);
                if (!sappBindingConfigSwitchItem.isPollerSuspender()) {
                    SappAddressOnOffStatus statusAddress = sappBindingConfigSwitchItem.getStatus();
                    if (statusAddress.getAddressType() == sappAddressType && statusAddress.getPnmasId().equals(pnmasId) && addressToUpdate == statusAddress.getAddress()) {
                        logger.debug("found binding to update {}", sappBindingConfigSwitchItem);
                        int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(), newState);
                        State stateToSet = result == statusAddress.getOnValue() ? OnOffType.ON : OnOffType.OFF;
                        if (!stateToSet.equals(item.getState())) {
                            eventPublisher.postUpdate(itemName, stateToSet);
                        }
                    }
                }
            } else if (item instanceof ContactItem) {
                SappBindingConfigContactItem sappBindingConfigContactItem = (SappBindingConfigContactItem) provider.getBindingConfig(itemName);
                SappAddressOpenClosedStatus statusAddress = sappBindingConfigContactItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType && statusAddress.getPnmasId().equals(pnmasId) && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigContactItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(), newState);
                    State stateToSet = result == statusAddress.getOpenValue() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                    if (!stateToSet.equals(item.getState())) {
                        eventPublisher.postUpdate(itemName, stateToSet);
                    }
                }
            } else if (item instanceof NumberItem) {
                SappBindingConfigNumberItem sappBindingConfigNumberItem = (SappBindingConfigNumberItem) provider.getBindingConfig(itemName);
                SappAddressDecimal address = sappBindingConfigNumberItem.getStatus();
                if (address.getAddressType() == sappAddressType && address.getPnmasId().equals(pnmasId) && addressToUpdate == address.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigNumberItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(address.getSubAddress(), newState);
                    State stateToSet = new DecimalType(address.scaledValue(result, address.getSubAddress()));
                    if (!stateToSet.equals(item.getState())) {
                        eventPublisher.postUpdate(itemName, stateToSet);
                    }
                }
            } else if (item instanceof RollershutterItem) {
                SappBindingConfigRollershutterItem sappBindingConfigRollershutterItem = (SappBindingConfigRollershutterItem) provider.getBindingConfig(itemName);
                SappAddressRollershutterStatus statusAddress = sappBindingConfigRollershutterItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType && statusAddress.getPnmasId().equals(pnmasId) && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigRollershutterItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(), newState);
                    State stateToSet = result == statusAddress.getOpenValue() ? PercentType.HUNDRED : (result == statusAddress.getClosedValue() ? PercentType.ZERO : PercentType.valueOf("50"));
                    if (!stateToSet.equals(item.getState())) {
                        eventPublisher.postUpdate(itemName, stateToSet);
                    }
                }
            } else if (item instanceof DimmerItem) {
                SappBindingConfigDimmerItem sappBindingConfigDimmerItem = (SappBindingConfigDimmerItem) provider.getBindingConfig(itemName);
                SappAddressDimmer statusAddress = sappBindingConfigDimmerItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType && statusAddress.getPnmasId().equals(pnmasId) && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigDimmerItem);
                    int result = statusAddress.scaledValue(SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(), newState), statusAddress.getSubAddress()).round(new MathContext(0, RoundingMode.HALF_EVEN)).intValue();
                    State stateToSet;
                    if (result <= PercentType.ZERO.intValue()) {
                        stateToSet = PercentType.ZERO;
                    } else if (result >= PercentType.HUNDRED.intValue()) {
                        stateToSet = PercentType.HUNDRED;
                    } else {
                        stateToSet = PercentType.valueOf(String.valueOf(result));
                    }
                    if (!stateToSet.equals(item.getState())) {
                        eventPublisher.postUpdate(itemName, stateToSet);
                    }
                }
            } else {
                logger.error("unimplemented item type: {}", item.getClass().getSimpleName());
            }
        } catch (ItemNotFoundException e) {
            logger.error("Item {} not found", itemName);
        }
    }
}
Also used : SappBindingConfigDimmerItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigDimmerItem) SappBindingConfigContactItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigContactItem) ContactItem(org.openhab.core.library.items.ContactItem) SappBindingConfigRollershutterItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigRollershutterItem) SappBindingConfigContactItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigContactItem) MathContext(java.math.MathContext) SappAddressOpenClosedStatus(org.openhab.binding.sapp.internal.model.SappAddressOpenClosedStatus) NumberItem(org.openhab.core.library.items.NumberItem) SappBindingConfigNumberItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigNumberItem) SappBindingConfigContactItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigContactItem) NumberItem(org.openhab.core.library.items.NumberItem) SappBindingConfigDimmerItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigDimmerItem) DimmerItem(org.openhab.core.library.items.DimmerItem) SwitchItem(org.openhab.core.library.items.SwitchItem) SappBindingConfigNumberItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigNumberItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) SappBindingConfigRollershutterItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigRollershutterItem) Item(org.openhab.core.items.Item) ContactItem(org.openhab.core.library.items.ContactItem) SappBindingConfigSwitchItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigSwitchItem) SappAddressOnOffStatus(org.openhab.binding.sapp.internal.model.SappAddressOnOffStatus) SappAddressDimmer(org.openhab.binding.sapp.internal.model.SappAddressDimmer) SappAddressDecimal(org.openhab.binding.sapp.internal.model.SappAddressDecimal) State(org.openhab.core.types.State) SappAddressRollershutterStatus(org.openhab.binding.sapp.internal.model.SappAddressRollershutterStatus) SappBindingConfigDimmerItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigDimmerItem) DimmerItem(org.openhab.core.library.items.DimmerItem) SappBindingConfigNumberItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigNumberItem) RollershutterItem(org.openhab.core.library.items.RollershutterItem) SappBindingConfigRollershutterItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigRollershutterItem) DecimalType(org.openhab.core.library.types.DecimalType) SappBindingConfigSwitchItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigSwitchItem) SwitchItem(org.openhab.core.library.items.SwitchItem) SappBindingConfigSwitchItem(org.openhab.binding.sapp.internal.configs.SappBindingConfigSwitchItem) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Aggregations

RollershutterItem (org.openhab.core.library.items.RollershutterItem)22 DimmerItem (org.openhab.core.library.items.DimmerItem)15 NumberItem (org.openhab.core.library.items.NumberItem)15 SwitchItem (org.openhab.core.library.items.SwitchItem)14 PercentType (org.openhab.core.library.types.PercentType)12 ColorItem (org.openhab.core.library.items.ColorItem)11 ContactItem (org.openhab.core.library.items.ContactItem)11 DecimalType (org.openhab.core.library.types.DecimalType)10 State (org.openhab.core.types.State)8 Item (org.openhab.core.items.Item)7 ItemNotFoundException (org.openhab.core.items.ItemNotFoundException)7 DateTimeItem (org.openhab.core.library.items.DateTimeItem)7 Calendar (java.util.Calendar)6 DateTimeType (org.openhab.core.library.types.DateTimeType)6 HSBType (org.openhab.core.library.types.HSBType)6 StringType (org.openhab.core.library.types.StringType)5 SappBindingConfigContactItem (org.openhab.binding.sapp.internal.configs.SappBindingConfigContactItem)4 SappBindingConfigDimmerItem (org.openhab.binding.sapp.internal.configs.SappBindingConfigDimmerItem)4 SappBindingConfigNumberItem (org.openhab.binding.sapp.internal.configs.SappBindingConfigNumberItem)4 SappBindingConfigRollershutterItem (org.openhab.binding.sapp.internal.configs.SappBindingConfigRollershutterItem)4