当前位置: 首页>>代码示例>>Java>>正文


Java Item.getState方法代码示例

本文整理汇总了Java中org.openhab.core.items.Item.getState方法的典型用法代码示例。如果您正苦于以下问题:Java Item.getState方法的具体用法?Java Item.getState怎么用?Java Item.getState使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.openhab.core.items.Item的用法示例。


在下文中一共展示了Item.getState方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: publish

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * Publish a persistence message for a given item.
 * 
 * Topic and template will be reformatted by String.format using the
 * following parameters:
 * 
 * <pre>
 * 	%1 item name 
 * 	%2 alias (as defined in mqtt.persist)
 * 	%3 item state 
 * 	%4 current timestamp
 * </pre>
 * 
 * @param item
 *            item which to persist the state of.
 * @param alias
 *            null or as defined in persistence configuration.
 * @throws Exception
 *             when no MQTT message could be sent.
 */
public void publish(Item item, String alias) throws Exception {

	Object state = item.getState().toString();
	
	if (item.getState() instanceof DecimalType) {
		state = ((DecimalType) item.getState()).toBigDecimal();
	} else if (item.getState() instanceof DateTimeType) {
		state = ((DateTimeType) item.getState()).getCalendar();
	} else if (item.getState() instanceof OnOffType) {
		state = item.getState().equals(OnOffType.ON) ? "1" : "0";
	} else if (item.getState() instanceof OpenClosedType) {
		state = item.getState().equals(OpenClosedType.OPEN) ? "1" : "0";
	} else if (item.getState() instanceof UpDownType) {
		state = item.getState().equals(UpDownType.UP) ? "1" : "0";
	}

	String message = format(messageTemplate, item.getName(), trimToEmpty(alias), state, currentTimeMillis());
	String destination = format(topic, item.getName(), trimToEmpty(alias), state, currentTimeMillis());
	
	channel.publish(destination, message.getBytes());
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:42,代码来源:MqttPersistencePublisher.java

示例2: getState

import org.openhab.core.items.Item; //导入方法依赖的package包/类
private StateTransformable getState(Item item) {
    StateTransformable state = null;
    if (item.getState() instanceof HSBType) {
        HSBType hsb = (HSBType) item.getState();
        state = new HSBData(hsb.getHue().longValue(), hsb.getHue().longValue(), hsb.getHue().longValue());
    } else if (item.getState() instanceof DateTimeType) {
        DateTimeType dt = (DateTimeType) item.getState();
        DateTimeDataType data = new DateTimeDataType(dt.toString());
        state = new DateTimeData(data);
    } else if (item.getState() instanceof DecimalType) {

    } else if (item.getState() instanceof OnOffType) {

    } else if (item.getState() instanceof OpenClosedType) {

    } else if (item.getState() instanceof PercentType) {

    } else if (item.getState() instanceof UpDownType) {

    }
    return state;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:23,代码来源:ItemStateRequestProcessor.java

示例3: store

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * @{inheritDoc
 */
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) {
		logger.warn("MongoDB not initialized");
		return;
	}

	// Connect to mongodb server if we're not already connected
	if (!isConnected()) {
		connectToDatabase();
	}

	// If we still didn't manage to connect, then return!
	if (!isConnected()) {
		logger.warn(
				"mongodb: No connection to database. Can not persist item '{}'! Will retry connecting to database next time.",
				item);
		return;
	}

	String realName = item.getName();
	String name = (alias != null) ? alias : realName;
	Object value = this.convertValue(item.getState());

	DBObject obj = new BasicDBObject();
	obj.put(FIELD_ID, new ObjectId());
	obj.put(FIELD_ITEM, name);
	obj.put(FIELD_REALNAME, realName);
	obj.put(FIELD_TIMESTAMP, new Date());
	obj.put(FIELD_VALUE, value);
	this.mongoCollection.save(obj);

	logger.debug("MongoDB save {}={}", name, value);
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:43,代码来源:MongoDBPersistenceService.java

示例4: store

import org.openhab.core.items.Item; //导入方法依赖的package包/类
@Override
public void store(Item item, String alias) {

	if (item.getState() instanceof UnDefType)
		return;

	if (alias == null)
		alias = item.getName();

	logger.debug("store called for {}", alias);

	State state = item.getState();
	if (item instanceof DimmerItem || item instanceof RollershutterItem) {
		state = item.getStateAs(PercentType.class);
	} else if (item instanceof ColorItem) {
		state = item.getStateAs(HSBType.class);
	}
	MapDBItem mItem = new MapDBItem();
	mItem.setName(alias);
	mItem.setState(state);
	mItem.setTimestamp(new Date());
	MapDBItem oldItem = map.put(alias, mItem);

	if (!commitSameState) {
		if (oldItem != null) {
			if (!oldItem.getState().toString().equals(state.toString())) {
				needsCommit = true;
			}
		}
	}
	logger.debug("Stored '{}' with state '{}' in mapdb database", alias,
			state.toString());
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:34,代码来源:MapDBPersistenceService.java

示例5: AlarmDecoderBindingConfig

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * Class that holds binding configuration information
 * @param type
 * @param address
 * @param feature
 * @param params
 */
public AlarmDecoderBindingConfig(Item item, ADMsgType type, String address,
		String feature,	HashMap<String, String> params) {
	m_item 		= item;
	m_type		= type;
	m_address	= address;
	m_feature	= feature;
	m_params	= params;
	m_itemState	= item.getState();
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:17,代码来源:AlarmDecoderBindingConfig.java

示例6: getRefreshCommands

import org.openhab.core.items.Item; //导入方法依赖的package包/类
private List<SatelMessage> getRefreshCommands(NewStatesEvent nse) {
	logger.trace("Gathering refresh commands from all items");

	List<SatelMessage> commands = new ArrayList<SatelMessage>();
	for (SatelBindingProvider provider : providers) {
		for (String itemName : provider.getItemNames()) {
			logger.trace("Getting refresh command from item: {}", itemName);

			SatelBindingConfig itemConfig = provider.getItemConfig(itemName);
			SatelMessage message = itemConfig.buildRefreshMessage(this.satelModule.getIntegraType());

			if (message == null || commands.contains(message)) {
				continue;
			}

			// either state has changed or this is status command, so likely
			// RTC has changed or state is Undefined, so get the latest
			// value from the module
			Item item = provider.getItem(itemName);
			if (item.getState() == UnDefType.UNDEF || (nse != null && nse.isNew(message.getCommand()))
					|| message.getCommand() == IntegraStatusCommand.COMMAND_CODE) {
				commands.add(message);
			}
		}
	}

	return commands;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:29,代码来源:SatelBinding.java

示例7: getState

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public State getState(Widget w) {
	String itemName = w.getItem();
	if(itemName!=null) {
		try {
			Item item = getItem(itemName);
			return item.getState();
		} catch (ItemNotFoundException e) {
			logger.error("Cannot retrieve item {} for widget {}", itemName, w.eClass().getInstanceTypeName());
		}
	}
	return UnDefType.UNDEF;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:16,代码来源:ItemUIRegistryImpl.java

示例8: getItemState

import org.openhab.core.items.Item; //导入方法依赖的package包/类
public State getItemState(String itemName) {
	try {
		Item item = itemRegistry.getItem(itemName);
		return item.getState();
	} catch (ItemNotFoundException e) {
		return null;
	}
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:9,代码来源:ItemUIRegistryImpl.java

示例9: store

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public void store(Item item, String alias) {
  if (item.getState() instanceof UnDefType) {
    return;
  }

  if (!isProperlyConfigured) {
    logger.warn("Configuration for influxdb 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 influxdb {}", name, value);

  // For now time is calculated by influxdb, may be this should be configurable?
  Serie serie = new Serie.Builder(name)
    .columns(VALUE_COLUMN_NAME)
    .values(value)
    .build();
  // serie.setColumns(new String[] {"time", VALUE_COLUMN_NAME});
  // Object[] point = new Object[] {System.currentTimeMillis(), value};

  try {
    influxDB.write(dbName, TimeUnit.MILLISECONDS, serie);
  } catch (RuntimeException e) {
    logger.error("storing failed with exception for item: {}", name);
    handleDatabaseException(e);
  }
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:50,代码来源:InfluxDBPersistenceService.java

示例10: store

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * @{inheritDoc
 */
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 DimmerItem || item instanceof RollershutterItem) {
		value = item.getStateAs(PercentType.class).toString();
	} else if (item instanceof ColorItem) {
		value = item.getStateAs(HSBType.class).toString();
	} else {
		// All other items should return the best format by default
		value = item.getState().toString();
	}

	String sqlCmd = null;
	//Statement statement = null;
	PreparedStatement statement = null;
	try {
		sqlCmd = new String("INSERT INTO " + tableName + " (TIME, VALUE) VALUES(NOW(),?) ON DUPLICATE KEY UPDATE VALUE=?;");
		statement = connection.prepareStatement(sqlCmd);
		statement.setString(1, item.getState().toString());
		statement.setString(2, item.getState().toString());
		statement.executeUpdate();

		logger.debug("mySQL: Stored item '{}' as '{}'[{}] in SQL database at {}.", item.getName(), item.getState()
				.toString(), value, (new java.util.Date()).toString());
		logger.debug("mySQL: {}", 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) {
			}
		}
	}
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:77,代码来源:MysqlPersistenceService.java

示例11: store

import org.openhab.core.items.Item; //导入方法依赖的package包/类
@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 perist it!");
		return;
	}
	
	if(!JpaConfiguration.isInitialized) {
		logger.warn("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 {
		pItem.setValue(StateHelper.toString(item.getState()));
	} 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");
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:47,代码来源:JpaPersistenceService.java

示例12: internalReceiveCommand

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
protected void internalReceiveCommand(String itemName, Command command) {
	try {
		logger.debug("internalReceiveCommand: itemName '{}', command '{}'", itemName, command);

		// Lookup the MiOS Unit name and property for this item
		String unitName = getMiosUnitName(itemName);

		MiosUnitConnector connector = getMiosConnector(unitName);
		if (connector == null) {
			logger.warn("Received command ({}) for item '{}' but no connector found for MiOS Unit '{}', ignoring",
					new Object[] { command.toString(), itemName, unitName });
			return;
		}

		if (!connector.isConnected()) {
			logger.warn(
					"Received command ({}) for item '{}' but the connection to the MiOS Unit '{}' is down, ignoring",
					new Object[] { command.toString(), itemName, unitName });
			return;
		}

		for (BindingProvider provider : providers) {
			if (provider instanceof MiosBindingProvider) {
				MiosBindingProviderImpl miosProvider = (MiosBindingProviderImpl) provider;
				MiosBindingConfig config = miosProvider.getMiosBindingConfig(itemName);

				if (config != null) {
					ItemRegistry reg = miosProvider.getItemRegistry();

					if (reg != null) {
						Item item = reg.getItem(config.getItemName());
						State state = item.getState();
						connector.invokeCommand(config, command, state);
					} else {
						logger.warn("internalReceiveCommand: Missing ItemRegistry for item '{}' command '{}'",
								itemName, command);
					}
				} else {
					logger.trace("internalReceiveCommand: Missing BindingConfig for item '{}' command '{}'",
							itemName, command);
				}
			}
		}

	} catch (Exception e) {
		logger.error("Error handling command", e);
	}
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:53,代码来源:MiosBinding.java

示例13: formatLabel

import org.openhab.core.items.Item; //导入方法依赖的package包/类
private String formatLabel(Item item, String itemName, String label) {
	// now insert the value, if the state is a string or decimal value and
	// there is some formatting pattern defined in the label
	// (i.e. it contains at least a %)
	if (itemName != null && label.contains("[")) {

		int indexOpenBracket = label.indexOf("[");
		int indexCloseBracket = label.indexOf("]");

		State state = null;
		String formatPattern = label.substring(indexOpenBracket + 1, indexCloseBracket);
		// TODO: TEE: we should find a more generic solution here! When
		// using indexes in formatString this 'contains' will fail again
		// and will cause an
		// 'java.util.IllegalFormatConversionException:
		// d != java.lang.String' later on when trying to format a
		// String
		// as %d (number).
		if (item != null) {
			if (label.contains("%d")) {
				// a number is requested
				state = item.getState();
				if (!(state instanceof DecimalType)) {
					state = item.getStateAs(DecimalType.class);
				}
			} else {
				state = item.getState();
			}
		}

		if (state == null || state instanceof UnDefType) {
			formatPattern = formatUndefined(formatPattern);
		} else if (state instanceof Type) {
			// The following exception handling has been added to work
			// around a Java bug with formatting
			// numbers. See http://bugs.sun.com/view_bug.do?bug_id=6476425
			// Without this catch, the whole sitemap, or page can not be
			// displayed!
			// This also handles IllegalFormatConverionException, which is a
			// subclass of IllegalArgument.
			try {
				formatPattern = ((Type) state).format(formatPattern);
			} catch (IllegalArgumentException e) {
				logger.warn("Exception while formatting value '{}' of item {} with format '{}': {}", state,
						itemName, formatPattern, e);
				formatPattern = new String("Err");
			}
		}

		label = label.substring(0, indexOpenBracket + 1) + formatPattern + label.substring(indexCloseBracket);
	}

	label = transform(label);

	return label;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:57,代码来源:ItemUIRegistryImpl.java

示例14: processColorDefinition

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
private String processColorDefinition(State state, List<ColorArray> colorList) {
	// Sanity check
	if(colorList == null) {
		return null;
	}
	if(colorList.size() == 0) {
		return null;
	}

	String colorString = null;

	// Check for the "arg". If it doesn't exist, assume there's just an
	// static colour
	if(colorList.size() == 1 && colorList.get(0).getState() == null) {
		colorString = colorList.get(0).getArg();
	}
	else {
		// Loop through all elements looking for the definition associated
		// with the supplied value
		for (ColorArray color : colorList) {
			// Use a local state variable in case it gets overridden below
			State cmpState = state;

			if(color.getState() == null) {
				logger.error("Error parsing color");
				continue;
			}

			// If there's an item defined here, get it's state
			if(color.getItem() != null) {
				// Try and find the item to test.
				// If it's not found, return visible
				Item item;
				try {
					item = itemRegistry.getItem(color.getItem());

					// Get the item state
					cmpState = item.getState();
				} catch (ItemNotFoundException e) {
					logger.warn("Cannot retrieve color item {} for widget", color.getItem());
				}
			}

			// Handle the sign
			String value;
			if(color.getSign() != null)
				value = color.getSign() + color.getState();
			else
				value = color.getState();

			if (matchStateToValue(cmpState, value, color.getCondition()) == true) {
				// We have the color for this value - break!
				colorString = color.getArg();
				break;
			}
		}
	}

	// Remove quotes off the colour - if they exist
	if(colorString == null)
		return null;

	if(colorString.startsWith("\"") && colorString.endsWith("\""))
		colorString = colorString.substring(1, colorString.length()-1);
	
	// Check if the color is a "standard" color - if so, we convert to the CSS ("#xxxxxx") format
	OpenhabColors stdColor = OpenhabColors.fromString(colorString);
	if(stdColor != null)
		colorString = stdColor.toString();

	return colorString;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:76,代码来源:ItemUIRegistryImpl.java

示例15: getVisiblity

import org.openhab.core.items.Item; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public boolean getVisiblity(Widget w) {
	// Default to visible if parameters not set
	List<VisibilityRule> ruleList = w.getVisibility();
	if(ruleList == null)
		return true;
	if(ruleList.size() == 0)
		return true;

	logger.debug("Checking visiblity for widget '{}'.", w.getLabel());

	for (VisibilityRule rule : w.getVisibility()) {
		if(rule.getItem() == null)
			continue;
		if(rule.getState() == null)
			continue;
		
		// Try and find the item to test.
		// If it's not found, return visible
		Item item;
		try {
			item = itemRegistry.getItem(rule.getItem());
		} catch (ItemNotFoundException e) {
			logger.error("Cannot retrieve visibility item {} for widget {}", rule.getItem(), w.eClass().getInstanceTypeName());

			// Default to visible!
			return true;
		}

		// Get the item state
		State state = item.getState();

		// Handle the sign
		String value;
		if(rule.getSign() != null)
			value = rule.getSign() + rule.getState();
		else
			value = rule.getState();

		if (matchStateToValue(state, value, rule.getCondition()) == true) {
			// We have the name for this value!
			return true;
		}
	}

	logger.debug("Widget {} is not visible.", w.getLabel());
	
	// The state wasn't in the list, so we don't display it
	return false;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:53,代码来源:ItemUIRegistryImpl.java


注:本文中的org.openhab.core.items.Item.getState方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。