use of org.openhab.core.library.types.IncreaseDecreaseType in project openhab1-addons by openhab.
the class ModbusSlave method setRegister.
/**
* Performs physical write to device when slave type is "holding" using Modbus FC06 function
*
* @param command command received from OpenHAB
* @param config
* @throws ModbusConnectionException when connection cannot be established
* @throws ModbusException ModbusIOException on IO errors, ModbusSlaveException with protocol level exceptions
* @throws ModbusUnexpectedTransactionIdException when response transaction id does not match the request
*/
protected void setRegister(Command command, ModbusBindingConfig config) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
int readIndex = config.readIndex;
int writeRegister = getStart() + config.writeIndex;
Register newValue;
if (command instanceof IncreaseDecreaseType) {
newValue = readCachedRegisterValue(readIndex);
if (newValue == null) {
logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
return;
}
if (command.equals(IncreaseDecreaseType.INCREASE)) {
newValue.setValue(newValue.getValue() + 1);
} else if (command.equals(IncreaseDecreaseType.DECREASE)) {
newValue.setValue(newValue.getValue() - 1);
}
} else if (command instanceof UpDownType) {
newValue = readCachedRegisterValue(readIndex);
if (newValue == null) {
logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
return;
}
if (command.equals(UpDownType.UP)) {
newValue.setValue(newValue.getValue() + 1);
} else if (command.equals(UpDownType.DOWN)) {
newValue.setValue(newValue.getValue() - 1);
}
} else if (command instanceof DecimalType) {
newValue = new SimpleRegister();
newValue.setValue(((DecimalType) command).intValue());
} else if (command instanceof OnOffType) {
newValue = new SimpleRegister();
if (command.equals(OnOffType.ON)) {
newValue.setValue(1);
} else if (command.equals(OnOffType.OFF)) {
newValue.setValue(0);
}
} else if (command instanceof OpenClosedType) {
newValue = new SimpleRegister();
if (command.equals(OpenClosedType.OPEN)) {
newValue.setValue(1);
} else if (command.equals(OpenClosedType.CLOSED)) {
newValue.setValue(0);
}
} else {
logger.warn("Item {} received unsupported command: {}. Not setting register.", config.getItemName(), command);
return;
}
ModbusRequest request = null;
if (writeMultipleRegisters) {
Register[] regs = new Register[1];
regs[0] = newValue;
request = new WriteMultipleRegistersRequest(writeRegister, regs);
} else {
request = new WriteSingleRegisterRequest(writeRegister, newValue);
}
request.setUnitID(getId());
logger.debug("ModbusSlave ({}): FC{} ref={} value={}", name, request.getFunctionCode(), writeRegister, newValue.getValue());
executeWriteRequest(request);
}
use of org.openhab.core.library.types.IncreaseDecreaseType 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;
}
use of org.openhab.core.library.types.IncreaseDecreaseType in project openhab1-addons by openhab.
the class SappBinding method executeSappCommand.
/**
* executes the real command on pnmas device
*/
private void executeSappCommand(String itemName, Command command) {
SappBindingProvider provider = findFirstMatchingBindingProvider(itemName);
if (provider == null) {
logger.error("cannot find a provider, skipping command");
}
try {
Item item = itemRegistry.getItem(itemName);
logger.debug("found item {}", item);
if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
SappBindingConfigSwitchItem sappBindingConfigSwitchItem = (SappBindingConfigSwitchItem) provider.getBindingConfig(itemName);
logger.debug("found binding {}", sappBindingConfigSwitchItem);
if (sappBindingConfigSwitchItem.isPollerSuspender()) {
if (pollingEnabled) {
// turning off polling
pollingEnabled = false;
// force updates of polling switches because polling is
updatePollingSwitchesState(provider);
// off
} else {
// turning on polling
provider.getSappUpdatePendingRequests().replaceAllPendingUpdateRequests(ALL_UPDATE_REQUEST_KEY);
pollingEnabled = true;
}
} else {
SappAddressOnOffControl controlAddress = sappBindingConfigSwitchItem.getControl();
if (!provider.getPnmasMap().containsKey(controlAddress.getPnmasId())) {
logger.error("bad pnmas id ({}) in binding ({}) ... skipping", controlAddress.getPnmasId(), sappBindingConfigSwitchItem);
return;
}
try {
if (command instanceof OnOffType) {
switch(controlAddress.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, controlAddress.getPnmasId(), controlAddress.getAddress(), controlAddress.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(controlAddress.getSubAddress(), command.equals(OnOffType.ON) ? controlAddress.getOnValue() : controlAddress.getOffValue(), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(controlAddress.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), controlAddress.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), controlAddress.getAddressType());
break;
}
} else {
logger.error("command {} not applicable", command.getClass().getSimpleName());
}
} catch (SappException e) {
logger.error("could not run sappcommand", e);
}
}
} else if (item instanceof NumberItem) {
SappBindingConfigNumberItem sappBindingConfigNumberItem = (SappBindingConfigNumberItem) provider.getBindingConfig(itemName);
logger.debug("found binding {}", sappBindingConfigNumberItem);
SappAddressDecimal address = sappBindingConfigNumberItem.getStatus();
if (!provider.getPnmasMap().containsKey(address.getPnmasId())) {
logger.error("bad pnmas id ({}) in binding ({}) ... skipping", address.getPnmasId(), sappBindingConfigNumberItem);
return;
}
try {
if (command instanceof DecimalType) {
switch(address.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, address.getPnmasId(), address.getAddress(), address.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(address.getSubAddress(), address.backScaledValue(((DecimalType) command).toBigDecimal()), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(address.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), address.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), address.getAddressType());
break;
}
} else {
logger.error("command {} not applicable", command.getClass().getSimpleName());
}
} catch (SappException e) {
logger.error("could not run sappcommand", e);
}
} else if (item instanceof RollershutterItem) {
SappBindingConfigRollershutterItem sappBindingConfigRollershutterItem = (SappBindingConfigRollershutterItem) provider.getBindingConfig(itemName);
logger.debug("found binding {}", sappBindingConfigRollershutterItem);
SappAddressRollershutterControl controlAddress = null;
if (command instanceof UpDownType && ((UpDownType) command) == UpDownType.UP) {
controlAddress = sappBindingConfigRollershutterItem.getUpControl();
} else if (command instanceof UpDownType && ((UpDownType) command) == UpDownType.DOWN) {
controlAddress = sappBindingConfigRollershutterItem.getDownControl();
} else if (command instanceof StopMoveType && ((StopMoveType) command) == StopMoveType.STOP) {
controlAddress = sappBindingConfigRollershutterItem.getStopControl();
}
if (controlAddress != null) {
if (!provider.getPnmasMap().containsKey(controlAddress.getPnmasId())) {
logger.error("bad pnmas id ({}) in binding ({}) ... skipping", controlAddress.getPnmasId(), sappBindingConfigRollershutterItem);
return;
}
try {
switch(controlAddress.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, controlAddress.getPnmasId(), controlAddress.getAddress(), controlAddress.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(controlAddress.getSubAddress(), controlAddress.getActivateValue(), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(controlAddress.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), controlAddress.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), controlAddress.getAddressType());
break;
}
} catch (SappException e) {
logger.error("could not run sappcommand", e);
}
} else {
logger.error("command {} not applicable", command.getClass().getSimpleName());
}
} else if (item instanceof DimmerItem) {
SappBindingConfigDimmerItem sappBindingConfigDimmerItem = (SappBindingConfigDimmerItem) provider.getBindingConfig(itemName);
logger.debug("found binding {}", sappBindingConfigDimmerItem);
SappAddressDimmer address = sappBindingConfigDimmerItem.getStatus();
if (!provider.getPnmasMap().containsKey(address.getPnmasId())) {
logger.error("bad pnmas id ({}) in binding ({}) ... skipping", address.getPnmasId(), sappBindingConfigDimmerItem);
return;
}
try {
if (command instanceof OnOffType) {
switch(address.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, address.getPnmasId(), address.getAddress(), address.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(address.getSubAddress(), ((OnOffType) command) == OnOffType.ON ? address.getOriginalMaxScale() : address.getOriginalMinScale(), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(address.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), address.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), address.getAddressType());
break;
}
} else if (command instanceof IncreaseDecreaseType) {
switch(address.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, address.getPnmasId(), address.getAddress(), address.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(address.getSubAddress(), ((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE ? Math.min(previousValue + address.getIncrement(), address.getOriginalMaxScale()) : Math.max(previousValue - address.getIncrement(), address.getOriginalMinScale()), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(address.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), address.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), address.getAddressType());
break;
}
} else if (command instanceof PercentType) {
switch(address.getAddressType()) {
case VIRTUAL:
{
// mask bits on previous value
int previousValue = getVirtualValue(provider, address.getPnmasId(), address.getAddress(), address.getSubAddress(), false);
int newValue = SappBindingConfigUtils.maskWithSubAddressAndSet(address.getSubAddress(), address.backScaledValue(((PercentType) command).toBigDecimal()), previousValue);
// update pnmas
SappPnmas pnmas = provider.getPnmasMap().get(address.getPnmasId());
SappCentralExecuter sappCentralExecuter = SappCentralExecuter.getInstance();
sappCentralExecuter.executeSapp7DCommand(pnmas.getIp(), pnmas.getPort(), address.getAddress(), newValue);
break;
}
default:
logger.error("cannot run {} on type {}", command.getClass().getSimpleName(), address.getAddressType());
break;
}
} else {
logger.error("command {} not applicable", command.getClass().getSimpleName());
}
} catch (SappException e) {
logger.error("could not run sappcommand", e);
}
} else {
logger.error("unimplemented item type: {}", item.getClass().getSimpleName());
}
} catch (ItemNotFoundException e) {
logger.error("Item {} not found", itemName);
}
}
use of org.openhab.core.library.types.IncreaseDecreaseType in project openhab1-addons by openhab.
the class PulseaudioBinding method internalReceiveCommand.
@Override
public void internalReceiveCommand(String itemName, Command command) {
PulseaudioBindingProvider provider = findFirstMatchingBindingProvider(itemName, command);
if (provider == null) {
logger.warn("doesn't find matching binding provider [itemName={}, command={}]", itemName, command);
return;
}
String audioItemName = provider.getItemName(itemName);
String serverId = provider.getServerId(itemName);
// Item item = provider.getItem(itemName);
String paCommand = provider.getCommand(itemName);
PulseaudioCommandTypeMapping pulseaudioCommandType = null;
if (paCommand != null && !paCommand.isEmpty()) {
try {
pulseaudioCommandType = PulseaudioCommandTypeMapping.valueOf(paCommand.toUpperCase());
} catch (IllegalArgumentException e) {
logger.warn("unknown command specified for the given itemName [itemName={}, audio-item-name={}, serverId={}, command={}] => querying for values aborted!", new Object[] { itemName, audioItemName, serverId, command });
}
}
PulseaudioClient client = clients.get(serverId);
if (client == null) {
// try to reconnect if the server is configured
if (serverConfigCache.containsKey(serverId)) {
connect(serverId, serverConfigCache.get(serverId));
client = clients.get(serverId);
}
}
if (client == null) {
logger.warn("does't find matching pulseaudio client [itemName={}, serverId={}]", itemName, serverId);
return;
}
if (audioItemName != null && !audioItemName.isEmpty()) {
AbstractAudioDeviceConfig audioItem = client.getGenericAudioItem(audioItemName);
if (audioItem == null) {
logger.warn("no corresponding audio-item found [audioItemName={}]", audioItemName);
return;
}
State updateState = UnDefType.UNDEF;
if (command instanceof IncreaseDecreaseType) {
int volume = audioItem.getVolume();
logger.debug(audioItemName + " volume is " + volume);
if (command.equals(IncreaseDecreaseType.INCREASE)) {
volume = Math.min(100, volume + 5);
}
if (command.equals(IncreaseDecreaseType.DECREASE)) {
volume = Math.max(0, volume - 5);
}
logger.debug("setting " + audioItemName + " volume to " + volume);
client.setVolumePercent(audioItem, volume);
updateState = new PercentType(volume);
} else if (command instanceof PercentType) {
client.setVolumePercent(audioItem, Integer.valueOf(command.toString()));
updateState = (PercentType) command;
} else if (command instanceof DecimalType) {
if (pulseaudioCommandType == null || pulseaudioCommandType.equals(PulseaudioCommandTypeMapping.VOLUME)) {
// set volume
client.setVolume(audioItem, Integer.valueOf(command.toString()));
updateState = (DecimalType) command;
}
// all other pulseaudioCommandType's for DecimalTypes are
// read-only and
// therefore we do nothing here
} else if (command instanceof OnOffType) {
if (pulseaudioCommandType == null) {
// Default behaviour when no command is specified => mute
client.setMute(audioItem, ((OnOffType) command).equals(OnOffType.ON));
updateState = (OnOffType) command;
} else {
switch(pulseaudioCommandType) {
case EXISTS:
// we better do nothing here
break;
case MUTED:
client.setMute(audioItem, ((OnOffType) command).equals(OnOffType.ON));
updateState = (OnOffType) command;
break;
case RUNNING:
case CORKED:
case SUSPENDED:
case IDLE:
// the state of an audio-item cannot be changed
break;
case ID:
case MODULE_ID:
// changed
break;
case VOLUME:
if (((OnOffType) command).equals(OnOffType.ON)) {
// Set Volume to 100%
client.setVolume(audioItem, 100);
} else {
// set volume to 0
client.setVolume(audioItem, 100);
}
updateState = (OnOffType) command;
break;
case SLAVE_SINKS:
// also an read-only field
break;
}
}
} else if (command instanceof StringType) {
if (pulseaudioCommandType != null) {
switch(pulseaudioCommandType) {
case CORKED:
case EXISTS:
case ID:
case IDLE:
case MODULE_ID:
case MUTED:
case RUNNING:
case SUSPENDED:
case VOLUME:
// no action here
break;
case SLAVE_SINKS:
if (audioItem instanceof Sink && ((Sink) audioItem).isCombinedSink()) {
// change the slave sinks of the given combined sink
// to the new value
Sink mainSink = (Sink) audioItem;
ArrayList<Sink> slaveSinks = new ArrayList<Sink>();
for (String slaveSinkName : StringUtils.split(command.toString(), ",")) {
Sink slaveSink = client.getSink(slaveSinkName);
if (slaveSink != null) {
slaveSinks.add(slaveSink);
}
}
logger.debug(slaveSinks.size() + " slave sinks");
if (slaveSinks.size() > 0) {
client.setCombinedSinkSlaves(mainSink, slaveSinks);
}
}
break;
}
}
}
if (!updateState.equals(UnDefType.UNDEF)) {
eventPublisher.postUpdate(itemName, updateState);
}
} else if (command instanceof StringType) {
// send the command directly to the pulseaudio server
client.sendCommand(command.toString());
eventPublisher.postUpdate(itemName, (StringType) command);
}
}
use of org.openhab.core.library.types.IncreaseDecreaseType in project openhab1-addons by openhab.
the class BenqProjectorBinding method sendCommandToProjector.
/**
* Send the command to the projector via configured transport and return the
* response string
*
* @param cfg
* Item binding configuration
* @param c
* command to be sent
* @return Response string from projector
*/
private String sendCommandToProjector(BenqProjectorBindingConfig cfg, Command c) {
Boolean cmdSent = false;
String response = "";
switch(cfg.mode) {
case POWER:
case MUTE:
if (c instanceof OnOffType) {
if ((OnOffType) c == OnOffType.ON) {
response = transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("ON"));
cmdSent = true;
} else if ((OnOffType) c == OnOffType.OFF) {
response = transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("OFF"));
cmdSent = true;
}
}
break;
case VOLUME:
if (c instanceof DecimalType) {
/* get current volume */
State currentVolState = queryProjector(cfg);
int currentVol = ((DecimalType) currentVolState).intValue();
int volLevel = ((DecimalType) c).intValue();
if (volLevel > this.MAX_VOLUME) {
volLevel = this.MAX_VOLUME;
} else if (volLevel < this.MIN_VOLUME) {
volLevel = this.MIN_VOLUME;
}
if (currentVol == volLevel) {
cmdSent = true;
}
while (currentVol != volLevel) {
if (currentVol < volLevel) {
transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("+"));
currentVol++;
cmdSent = true;
} else {
transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("-"));
currentVol--;
cmdSent = true;
}
}
} else if (c instanceof IncreaseDecreaseType) {
if ((IncreaseDecreaseType) c == IncreaseDecreaseType.INCREASE) {
transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("+"));
cmdSent = true;
} else if ((IncreaseDecreaseType) c == IncreaseDecreaseType.DECREASE) {
transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString("-"));
cmdSent = true;
}
}
/* get final volume */
response = transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandQueryString());
break;
case LAMP_HOURS:
logger.warn("Cannot send command to set lamp hours - not a valid operation!");
break;
case SOURCE_NUMBER:
if (c instanceof DecimalType) {
DecimalType sourceIdx = (DecimalType) c;
String cmd = BenqProjectorSourceMapping.getStringFromMapping(sourceIdx.intValue());
if (cmd.isEmpty() == false) {
response = transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString(cmd));
cmdSent = true;
}
}
break;
case SOURCE_STRING:
if (c instanceof StringType) {
StringType sourceStr = (StringType) c;
int mappingIdx = BenqProjectorSourceMapping.getMappingFromString(sourceStr.toString());
if (// double check this is a valid mapping
mappingIdx != -1) {
response = transport.sendCommandExpectResponse(cfg.mode.getItemModeCommandSetString(sourceStr.toString()));
cmdSent = true;
}
}
break;
default:
logger.error("Unexpected Item Mode!");
break;
}
if (cmdSent == false) {
logger.error("Unable to convert item command to projector state: Command=" + c);
}
return response;
}
Aggregations