use of org.openhab.core.types.UnDefType in project openhab1-addons by openhab.
the class JpaPersistenceService method store.
@Override
public void store(Item item, String alias) {
logger.debug("Storing item: {}", item.getName());
if (item.getState() instanceof UnDefType) {
logger.debug("This item is of undefined type. Cannot persist it!");
return;
}
if (!JpaConfiguration.isInitialized) {
logger.debug("Trying to create EntityManagerFactory but we don't have configuration yet!");
return;
}
// determine item name to be stored
String name = (alias != null) ? alias : item.getName();
JpaPersistentItem pItem = new JpaPersistentItem();
try {
String newValue = StateHelper.toString(item.getState());
pItem.setValue(newValue);
logger.debug("Stored new value: {}", newValue);
} catch (Exception e1) {
logger.error("Error on converting state value to string: {}", e1.getMessage());
return;
}
pItem.setName(name);
pItem.setRealName(item.getName());
pItem.setTimestamp(new Date());
EntityManager em = getEntityManagerFactory().createEntityManager();
try {
logger.debug("Persisting item...");
// In RESOURCE_LOCAL calls to EntityManager require a begin/commit
em.getTransaction().begin();
em.persist(pItem);
em.getTransaction().commit();
logger.debug("Persisting item...done");
} catch (Exception e) {
logger.error("Error on persisting item! Rolling back!");
logger.error(e.getMessage(), e);
em.getTransaction().rollback();
} finally {
em.close();
}
logger.debug("Storing item...done");
}
use of org.openhab.core.types.UnDefType 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) {
}
}
}
}
use of org.openhab.core.types.UnDefType 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);
}
}
use of org.openhab.core.types.UnDefType in project openhab1-addons by openhab.
the class CaldavPersistenceService method store.
@Override
public void store(Item item, String alias) {
if (item.getState() instanceof UnDefType) {
return;
}
DateTime dateOffset = DateTime.now().plusDays(futureOffset);
if (alias == null) {
alias = item.getName();
}
State state = item.getState();
logger.trace("persisting item: {}", item);
if (!singleEvents) {
// try to create events with correct ON OFF duration
final CaldavItem lastOn = this.findLastOn(alias, state);
if (lastOn != null) {
if (isOff(item.getState())) {
CalDavEvent event = lastOn.getEvent();
event.setLastChanged(DateTime.now());
String offContent = EventUtils.createEnd(alias, state);
event.setContent(event.getContent() + "\n" + offContent);
event.setEnd(dateOffset);
logger.debug("existing event found, updated for persistence: {}", event);
this.calDavLoader.addEvent(event);
} else {
CalDavEvent event = lastOn.getEvent();
event.setLastChanged(dateOffset);
String offContent = EventUtils.createBetween(alias, state);
event.setContent(event.getContent() + "\n" + offContent);
logger.debug("existing event found, updated for persistence: {}", event);
this.calDavLoader.addEvent(event);
}
return;
}
}
logger.debug("creating new event");
CalDavEvent event = new CalDavEvent();
final String id = UUID.randomUUID().toString();
event.setId(id);
event.setName(alias);
event.setLastChanged(DateTime.now());
event.setContent(EventUtils.createBegin(alias, state));
event.setStart(dateOffset);
event.setEnd(dateOffset.plusMinutes(duration));
event.setCalendarId(calendarId);
event.setFilename("openHAB-" + id);
logger.debug("new event for persistence created: {}", event);
this.calDavLoader.addEvent(event);
}
use of org.openhab.core.types.UnDefType in project openhab1-addons by openhab.
the class DynamoDBPersistenceService method store.
/**
* {@inheritDoc}
*/
@Override
public void store(Item item, String alias) {
if (item.getState() instanceof UnDefType) {
logger.debug("Undefined item state received. Not storing item.");
return;
}
if (!isProperlyConfigured) {
logger.warn("Configuration for dynamodb not yet loaded or broken. Not storing item.");
return;
}
if (!maybeConnectAndCheckConnection()) {
logger.warn("DynamoDB not connected. Not storing item.");
return;
}
String realName = item.getName();
String name = (alias != null) ? alias : realName;
Date time = new Date(System.currentTimeMillis());
State state = item.getState();
logger.trace("Tried to get item from item class {}, state is {}", item.getClass(), state.toString());
DynamoDBItem<?> dynamoItem = AbstractDynamoDBItem.fromState(name, state, time);
DynamoDBMapper mapper = getDBMapper(tableNameResolver.fromItem(dynamoItem));
if (!createTable(mapper, dynamoItem.getClass())) {
logger.warn("Table creation failed. Not storing item");
return;
}
try {
logger.debug("storing {} in dynamo. Serialized value {}. Original Item: {}", name, state, item);
mapper.save(dynamoItem);
logger.debug("Sucessfully stored item {}", item);
} catch (AmazonClientException e) {
logger.error("Error storing object to dynamo: {}", e.getMessage());
}
}
Aggregations