Search in sources :

Example 16 with OnOffType

use of org.eclipse.smarthome.core.library.types.OnOffType in project smarthome by eclipse.

the class TunableWhiteThingHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    logger.trace("received command {} in channel {}", command, channelUID);
    ValueSet targetValueSet = new ValueSet(fadeTime, -1);
    switch(channelUID.getId()) {
        case CHANNEL_BRIGHTNESS:
            {
                if (command instanceof PercentType || command instanceof DecimalType) {
                    PercentType brightness = (command instanceof PercentType) ? (PercentType) command : Util.toPercentValue(((DecimalType) command).intValue());
                    logger.trace("adding fade to channels in thing {}", this.thing.getUID());
                    targetValueSet.addValue(Util.toDmxValue(Util.toDmxValue(brightness) * (100 - currentColorTemperature.intValue()) / 100));
                    targetValueSet.addValue(Util.toDmxValue(Util.toDmxValue(brightness) * currentColorTemperature.intValue() / 100));
                } else if (command instanceof OnOffType) {
                    logger.trace("adding {} fade to channels in thing {}", command, this.thing.getUID());
                    targetValueSet = ((OnOffType) command).equals(OnOffType.ON) ? turnOnValue : turnOffValue;
                } else if (command instanceof IncreaseDecreaseType) {
                    if (isDimming && ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
                        logger.trace("stopping fade in thing {}", this.thing.getUID());
                        channels.forEach(DmxChannel::clearAction);
                        isDimming = false;
                        return;
                    } else {
                        logger.trace("starting {} fade in thing {}", command, this.thing.getUID());
                        targetValueSet = ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE) ? turnOnValue : turnOffValue;
                        targetValueSet.setFadeTime(dimTime);
                        isDimming = true;
                    }
                } else if (command instanceof RefreshType) {
                    logger.trace("sending update on refresh to channel {}:brightness", this.thing.getUID());
                    currentValues.set(0, channels.get(0).getValue());
                    currentValues.set(1, channels.get(1).getValue());
                    updateCurrentBrightnessAndTemperature();
                    updateState(channelUID, currentBrightness);
                    return;
                } else {
                    logger.debug("command {} not supported in channel {}:brightness", command.getClass(), this.thing.getUID());
                    return;
                }
                break;
            }
        case CHANNEL_BRIGHTNESS_CW:
            if (command instanceof RefreshType) {
                logger.trace("sending update on refresh to channel {}:brightness_cw", this.thing.getUID());
                currentValues.set(0, channels.get(0).getValue());
                updateState(channelUID, Util.toPercentValue(currentValues.get(0)));
                return;
            } else {
                logger.debug("command {} not supported in channel {}:brightness_cw", command.getClass(), this.thing.getUID());
                return;
            }
        case CHANNEL_BRIGHTNESS_WW:
            if (command instanceof RefreshType) {
                logger.trace("sending update on refresh to channel {}:brightness_ww", this.thing.getUID());
                currentValues.set(1, channels.get(1).getValue());
                updateState(channelUID, Util.toPercentValue(currentValues.get(1)));
                return;
            } else {
                logger.debug("command {} not supported in channel {}:brightness_ww", command.getClass(), this.thing.getUID());
                return;
            }
        case CHANNEL_COLOR_TEMPERATURE:
            {
                if (command instanceof PercentType) {
                    PercentType colorTemperature = (PercentType) command;
                    targetValueSet.addValue(Util.toDmxValue(Util.toDmxValue(currentBrightness) * (100 - colorTemperature.intValue()) / 100));
                    targetValueSet.addValue(Util.toDmxValue(Util.toDmxValue(currentBrightness) * colorTemperature.intValue() / 100));
                } else if (command instanceof RefreshType) {
                    logger.trace("sending update on refresh to channel {}:color_temperature", this.thing.getUID());
                    currentValues.set(0, channels.get(0).getValue());
                    currentValues.set(1, channels.get(1).getValue());
                    updateCurrentBrightnessAndTemperature();
                    updateState(channelUID, currentColorTemperature);
                    return;
                } else {
                    logger.debug("command {} not supported in channel {}:color_temperature", command.getClass(), this.thing.getUID());
                    return;
                }
                break;
            }
        default:
            logger.debug("channel {} not supported in thing {}", channelUID.getId(), this.thing.getUID());
            return;
    }
    final ValueSet valueSet = targetValueSet;
    IntStream.range(0, channels.size()).forEach(i -> {
        channels.get(i).setChannelAction(new FadeAction(valueSet.getFadeTime(), channels.get(i).getValue(), valueSet.getValue(i), valueSet.getHoldTime()));
    });
}
Also used : FadeAction(org.eclipse.smarthome.binding.dmx.internal.action.FadeAction) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) IncreaseDecreaseType(org.eclipse.smarthome.core.library.types.IncreaseDecreaseType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) RefreshType(org.eclipse.smarthome.core.types.RefreshType) ValueSet(org.eclipse.smarthome.binding.dmx.internal.ValueSet)

Example 17 with OnOffType

use of org.eclipse.smarthome.core.library.types.OnOffType in project smarthome by eclipse.

the class PersistenceResource method getItemHistoryDTO.

private Response getItemHistoryDTO(String serviceId, String itemName, String timeBegin, String timeEnd, int pageNumber, int pageLength, boolean boundary) {
    // Benchmarking timer...
    long timerStart = System.currentTimeMillis();
    // If serviceId is null, then use the default service
    PersistenceService service = null;
    String effectiveServiceId = serviceId != null ? serviceId : persistenceServiceRegistry.getDefaultId();
    service = persistenceServiceRegistry.get(effectiveServiceId);
    if (service == null) {
        logger.debug("Persistence service not found '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not found: " + effectiveServiceId);
    }
    if (!(service instanceof QueryablePersistenceService)) {
        logger.debug("Persistence service not queryable '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not queryable: " + effectiveServiceId);
    }
    QueryablePersistenceService qService = (QueryablePersistenceService) service;
    ZonedDateTime dateTimeBegin = ZonedDateTime.now();
    ZonedDateTime dateTimeEnd = dateTimeBegin;
    if (timeBegin != null) {
        dateTimeBegin = convertTime(timeBegin);
    }
    if (timeEnd != null) {
        dateTimeEnd = convertTime(timeEnd);
    }
    // End now...
    if (dateTimeEnd.toEpochSecond() == 0) {
        dateTimeEnd = ZonedDateTime.of(LocalDateTime.now(), timeZoneProvider.getTimeZone());
    }
    if (dateTimeBegin.toEpochSecond() == 0) {
        // Default to 1 days data if the times are the same or the start time is newer
        // than the end time
        dateTimeBegin = ZonedDateTime.of(dateTimeEnd.toLocalDateTime().plusDays(-1), timeZoneProvider.getTimeZone());
    }
    // than the end time
    if (dateTimeBegin.isAfter(dateTimeEnd) || dateTimeBegin.isEqual(dateTimeEnd)) {
        dateTimeBegin = ZonedDateTime.of(dateTimeEnd.toLocalDateTime().plusDays(-1), timeZoneProvider.getTimeZone());
    }
    FilterCriteria filter;
    Iterable<HistoricItem> result;
    State state = null;
    Long quantity = 0l;
    ItemHistoryDTO dto = new ItemHistoryDTO();
    dto.name = itemName;
    filter = new FilterCriteria();
    filter.setItemName(itemName);
    // (or not at all if there's no change during the graph period)
    if (boundary) {
        // Get the value before the start time.
        filter.setEndDate(dateTimeBegin);
        filter.setPageSize(1);
        filter.setOrdering(Ordering.DESCENDING);
        result = qService.query(filter);
        if (result != null && result.iterator().hasNext()) {
            dto.addData(dateTimeBegin.toInstant().toEpochMilli(), result.iterator().next().getState());
            quantity++;
        }
    }
    if (pageLength == 0) {
        filter.setPageNumber(0);
        filter.setPageSize(Integer.MAX_VALUE);
    } else {
        filter.setPageNumber(pageNumber);
        filter.setPageSize(pageLength);
    }
    filter.setBeginDate(dateTimeBegin);
    filter.setEndDate(dateTimeEnd);
    filter.setOrdering(Ordering.ASCENDING);
    result = qService.query(filter);
    if (result != null) {
        Iterator<HistoricItem> it = result.iterator();
        // Iterate through the data
        while (it.hasNext()) {
            HistoricItem historicItem = it.next();
            state = historicItem.getState();
            // to avoid diagonal lines
            if (state instanceof OnOffType || state instanceof OpenClosedType) {
                dto.addData(historicItem.getTimestamp().getTime(), state);
            }
            dto.addData(historicItem.getTimestamp().getTime(), state);
            quantity++;
        }
    }
    if (boundary) {
        // Get the value after the end time.
        filter.setBeginDate(dateTimeEnd);
        filter.setPageSize(1);
        filter.setOrdering(Ordering.ASCENDING);
        result = qService.query(filter);
        if (result != null && result.iterator().hasNext()) {
            dto.addData(dateTimeEnd.toInstant().toEpochMilli(), result.iterator().next().getState());
            quantity++;
        }
    }
    dto.datapoints = Long.toString(quantity);
    logger.debug("Persistence returned {} rows in {}ms", dto.datapoints, System.currentTimeMillis() - timerStart);
    return JSONResponse.createResponse(Status.OK, dto, "");
}
Also used : FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ItemHistoryDTO(org.eclipse.smarthome.core.persistence.dto.ItemHistoryDTO) ZonedDateTime(java.time.ZonedDateTime) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) State(org.eclipse.smarthome.core.types.State) OpenClosedType(org.eclipse.smarthome.core.library.types.OpenClosedType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Example 18 with OnOffType

use of org.eclipse.smarthome.core.library.types.OnOffType in project smarthome by eclipse.

the class HueLightHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    HueBridgeHandler hueBridge = getHueBridgeHandler();
    if (hueBridge == null) {
        logger.warn("hue bridge handler not found. Cannot handle command without bridge.");
        return;
    }
    FullLight light = getLight();
    if (light == null) {
        logger.debug("hue light not known on bridge. Cannot handle command.");
        return;
    }
    StateUpdate lightState = null;
    switch(channelUID.getId()) {
        case CHANNEL_COLORTEMPERATURE:
            if (command instanceof PercentType) {
                lightState = LightStateConverter.toColorTemperatureLightState((PercentType) command);
            } else if (command instanceof OnOffType) {
                lightState = LightStateConverter.toOnOffLightState((OnOffType) command);
                if (isOsramPar16) {
                    lightState = addOsramSpecificCommands(lightState, (OnOffType) command);
                }
            } else if (command instanceof IncreaseDecreaseType) {
                lightState = convertColorTempChangeToStateUpdate((IncreaseDecreaseType) command, light);
            }
            break;
        case CHANNEL_BRIGHTNESS:
            if (command instanceof PercentType) {
                lightState = LightStateConverter.toBrightnessLightState((PercentType) command);
            } else if (command instanceof OnOffType) {
                lightState = LightStateConverter.toOnOffLightState((OnOffType) command);
                if (isOsramPar16) {
                    lightState = addOsramSpecificCommands(lightState, (OnOffType) command);
                }
            } else if (command instanceof IncreaseDecreaseType) {
                lightState = convertBrightnessChangeToStateUpdate((IncreaseDecreaseType) command, light);
            }
            break;
        case CHANNEL_SWITCH:
            logger.trace("CHANNEL_SWITCH handling command {}", command);
            if (command instanceof OnOffType) {
                lightState = LightStateConverter.toOnOffLightState((OnOffType) command);
                if (isOsramPar16) {
                    lightState = addOsramSpecificCommands(lightState, (OnOffType) command);
                }
            }
            break;
        case CHANNEL_COLOR:
            if (command instanceof HSBType) {
                HSBType hsbCommand = (HSBType) command;
                if (hsbCommand.getBrightness().intValue() == 0) {
                    lightState = LightStateConverter.toOnOffLightState(OnOffType.OFF);
                } else {
                    lightState = LightStateConverter.toColorLightState(hsbCommand);
                }
            } else if (command instanceof PercentType) {
                lightState = LightStateConverter.toBrightnessLightState((PercentType) command);
            } else if (command instanceof OnOffType) {
                lightState = LightStateConverter.toOnOffLightState((OnOffType) command);
            } else if (command instanceof IncreaseDecreaseType) {
                lightState = convertBrightnessChangeToStateUpdate((IncreaseDecreaseType) command, light);
            }
            break;
        case CHANNEL_ALERT:
            if (command instanceof StringType) {
                lightState = LightStateConverter.toAlertState((StringType) command);
                if (lightState == null) {
                    // Unsupported StringType is passed. Log a warning
                    // message and return.
                    logger.warn("Unsupported String command: {}. Supported commands are: {}, {}, {} ", command, LightStateConverter.ALERT_MODE_NONE, LightStateConverter.ALERT_MODE_SELECT, LightStateConverter.ALERT_MODE_LONG_SELECT);
                    return;
                } else {
                    scheduleAlertStateRestore(command);
                }
            }
            break;
        case CHANNEL_EFFECT:
            if (command instanceof OnOffType) {
                lightState = LightStateConverter.toOnOffEffectState((OnOffType) command);
            }
            break;
    }
    if (lightState != null) {
        hueBridge.updateLightState(light, lightState);
    } else {
        logger.warn("Command sent to an unknown channel id: {}", channelUID);
    }
}
Also used : StateUpdate(org.eclipse.smarthome.binding.hue.internal.StateUpdate) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) StringType(org.eclipse.smarthome.core.library.types.StringType) IncreaseDecreaseType(org.eclipse.smarthome.core.library.types.IncreaseDecreaseType) FullLight(org.eclipse.smarthome.binding.hue.internal.FullLight) PercentType(org.eclipse.smarthome.core.library.types.PercentType) HSBType(org.eclipse.smarthome.core.library.types.HSBType)

Example 19 with OnOffType

use of org.eclipse.smarthome.core.library.types.OnOffType in project smarthome by eclipse.

the class WemoLightHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (command instanceof RefreshType) {
        try {
            getDeviceState();
        } catch (Exception e) {
            logger.debug("Exception during poll : {}", e);
        }
    } else {
        Configuration configuration = getConfig();
        configuration.get(DEVICE_ID);
        WemoBridgeHandler wemoBridge = getWemoBridgeHandler();
        if (wemoBridge == null) {
            logger.debug("wemoBridgeHandler not found, cannot handle command");
            return;
        }
        String devUDN = "uuid:" + wemoBridge.getThing().getConfiguration().get(UDN).toString();
        logger.trace("WeMo Bridge to send command to : {}", devUDN);
        String value = null;
        String capability = null;
        switch(channelUID.getId()) {
            case CHANNEL_BRIGHTNESS:
                capability = "10008";
                if (command instanceof PercentType) {
                    int newBrightness = ((PercentType) command).intValue();
                    logger.trace("wemoLight received Value {}", newBrightness);
                    int value1 = Math.round(newBrightness * 255 / 100);
                    value = value1 + ":0";
                    currentBrightness = newBrightness;
                } else if (command instanceof OnOffType) {
                    switch(command.toString()) {
                        case "ON":
                            value = "255:0";
                            break;
                        case "OFF":
                            value = "0:0";
                            break;
                    }
                } else if (command instanceof IncreaseDecreaseType) {
                    int newBrightness;
                    switch(command.toString()) {
                        case "INCREASE":
                            currentBrightness = currentBrightness + DIM_STEPSIZE;
                            newBrightness = Math.round(currentBrightness * 255 / 100);
                            if (newBrightness > 255) {
                                newBrightness = 255;
                            }
                            value = newBrightness + ":0";
                            break;
                        case "DECREASE":
                            currentBrightness = currentBrightness - DIM_STEPSIZE;
                            newBrightness = Math.round(currentBrightness * 255 / 100);
                            if (newBrightness < 0) {
                                newBrightness = 0;
                            }
                            value = newBrightness + ":0";
                            break;
                    }
                }
                break;
            case CHANNEL_STATE:
                capability = "10006";
                switch(command.toString()) {
                    case "ON":
                        value = "1";
                        break;
                    case "OFF":
                        value = "0";
                        break;
                }
                break;
        }
        try {
            String soapHeader = "\"urn:Belkin:service:bridge:1#SetDeviceStatus\"";
            String content = "<?xml version=\"1.0\"?>" + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<s:Body>" + "<u:SetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceStatusList>" + "&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;DeviceStatus&gt;&lt;DeviceID&gt;" + wemoLightID + "&lt;/DeviceID&gt;&lt;IsGroupAction&gt;NO&lt;/IsGroupAction&gt;&lt;CapabilityID&gt;" + capability + "&lt;/CapabilityID&gt;&lt;CapabilityValue&gt;" + value + "&lt;/CapabilityValue&gt;&lt;/DeviceStatus&gt;" + "</DeviceStatusList>" + "</u:SetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
            String wemoURL = getWemoURL();
            if (wemoURL != null && capability != null && value != null) {
                String wemoCallResponse = WemoHttpCall.executeCall(wemoURL, soapHeader, content);
                if (wemoCallResponse != null) {
                    if (capability != null && capability.equals("10008") && value != null) {
                        OnOffType binaryState = null;
                        binaryState = value.equals("0") ? OnOffType.OFF : OnOffType.ON;
                        if (binaryState != null) {
                            updateState(CHANNEL_STATE, binaryState);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not send command to WeMo Bridge", e);
        }
    }
}
Also used : Configuration(org.eclipse.smarthome.config.core.Configuration) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) IncreaseDecreaseType(org.eclipse.smarthome.core.library.types.IncreaseDecreaseType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) RefreshType(org.eclipse.smarthome.core.types.RefreshType)

Example 20 with OnOffType

use of org.eclipse.smarthome.core.library.types.OnOffType in project smarthome by eclipse.

the class WemoLightHandler method getDeviceState.

/**
 * The {@link getDeviceState} is used for polling the actual state of a WeMo Light and updating the according
 * channel states.
 */
public void getDeviceState() {
    logger.debug("Request actual state for LightID '{}'", wemoLightID);
    try {
        String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\"";
        String content = "<?xml version=\"1.0\"?>" + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<s:Body>" + "<u:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>" + wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
        String wemoURL = getWemoURL();
        if (wemoURL != null) {
            String wemoCallResponse = WemoHttpCall.executeCall(wemoURL, soapHeader, content);
            if (wemoCallResponse != null) {
                wemoCallResponse = StringEscapeUtils.unescapeXml(wemoCallResponse);
                String response = StringUtils.substringBetween(wemoCallResponse, "<CapabilityValue>", "</CapabilityValue>");
                logger.trace("wemoNewLightState = {}", response);
                String[] splitResponse = response.split(",");
                if (splitResponse[0] != null) {
                    OnOffType binaryState = null;
                    binaryState = splitResponse[0].equals("0") ? OnOffType.OFF : OnOffType.ON;
                    if (binaryState != null) {
                        updateState(CHANNEL_STATE, binaryState);
                    }
                }
                if (splitResponse[1] != null) {
                    String[] splitBrightness = splitResponse[1].split(":");
                    if (splitBrightness[0] != null) {
                        int newBrightnessValue = Integer.valueOf(splitBrightness[0]);
                        int newBrightness = Math.round(newBrightnessValue * 100 / 255);
                        logger.trace("newBrightness = {}", newBrightness);
                        State newBrightnessState = new PercentType(newBrightness);
                        updateState(CHANNEL_BRIGHTNESS, newBrightnessState);
                        currentBrightness = newBrightness;
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not retrieve new Wemo light state", e);
    }
}
Also used : OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) State(org.eclipse.smarthome.core.types.State) PercentType(org.eclipse.smarthome.core.library.types.PercentType)

Aggregations

OnOffType (org.eclipse.smarthome.core.library.types.OnOffType)21 PercentType (org.eclipse.smarthome.core.library.types.PercentType)10 RefreshType (org.eclipse.smarthome.core.types.RefreshType)8 IncreaseDecreaseType (org.eclipse.smarthome.core.library.types.IncreaseDecreaseType)7 State (org.eclipse.smarthome.core.types.State)7 DecimalType (org.eclipse.smarthome.core.library.types.DecimalType)6 ValueSet (org.eclipse.smarthome.binding.dmx.internal.ValueSet)4 FadeAction (org.eclipse.smarthome.binding.dmx.internal.action.FadeAction)4 StringType (org.eclipse.smarthome.core.library.types.StringType)4 HSBType (org.eclipse.smarthome.core.library.types.HSBType)3 ZonedDateTime (java.time.ZonedDateTime)2 BaseDmxChannel (org.eclipse.smarthome.binding.dmx.internal.multiverse.BaseDmxChannel)2 DmxChannel (org.eclipse.smarthome.binding.dmx.internal.multiverse.DmxChannel)2 OpenClosedType (org.eclipse.smarthome.core.library.types.OpenClosedType)2 FilterCriteria (org.eclipse.smarthome.core.persistence.FilterCriteria)2 HistoricItem (org.eclipse.smarthome.core.persistence.HistoricItem)2 JavaOSGiTest (org.eclipse.smarthome.test.java.JavaOSGiTest)2 Test (org.junit.Test)2 BasicStroke (java.awt.BasicStroke)1 Color (java.awt.Color)1