org.eclipse.smarthome.core.types.Command Java Examples

The following examples show how to use org.eclipse.smarthome.core.types.Command. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public void playTrack(Command command) {
    if (command != null && command instanceof DecimalType) {
        try {
            ZonePlayerHandler coordinator = getCoordinatorHandler();

            String trackNumber = String.valueOf(((DecimalType) command).intValue());

            coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");

            // seek the track - warning, we do not check if the tracknumber falls in the boundary of the queue
            coordinator.setPositionTrack(trackNumber);

            // take the system off mute
            coordinator.setMute(OnOffType.OFF);

            // start jammin'
            coordinator.play();
        } catch (IllegalStateException e) {
            logger.debug("Cannot play track ({})", e.getMessage());
        }
    }
}
 
Example #2
Source File: SystemOffsetProfileTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testQuantityTypeOnCommandFromHandler() {
    ProfileCallback callback = mock(ProfileCallback.class);
    SystemOffsetProfile offsetProfile = createProfile(callback, "3°C");

    Command cmd = new QuantityType<Temperature>("23°C");
    offsetProfile.onCommandFromHandler(cmd);

    ArgumentCaptor<Command> capture = ArgumentCaptor.forClass(Command.class);
    verify(callback, times(1)).sendCommand(capture.capture());

    Command result = capture.getValue();
    @SuppressWarnings("unchecked")
    QuantityType<Temperature> decResult = (QuantityType<Temperature>) result;
    assertEquals(26, decResult.intValue());
    assertEquals(SIUnits.CELSIUS, decResult.getUnit());
}
 
Example #3
Source File: SonyAudioHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public void handleVolumeCommand(Command command, ChannelUID channelUID, int zone) throws IOException {
    if (command instanceof RefreshType) {
        try {
            logger.debug("handleVolumeCommand RefreshType {}", zone);
            SonyAudioConnection.SonyAudioVolume result = volumeCache[zone].getValue();
            if (result != null) {
                updateState(channelUID, new PercentType(result.volume));
            }
        } catch (CompletionException ex) {
            throw new IOException(ex.getCause());
        }
    }
    if (command instanceof PercentType) {
        logger.debug("handleVolumeCommand PercentType set {} {}", zone, command);
        connection.setVolume(((PercentType) command).intValue(), zone);
    }
    if (command instanceof IncreaseDecreaseType) {
        logger.debug("handleVolumeCommand IncreaseDecreaseType set {} {}", zone, command);
        String change = command == IncreaseDecreaseType.INCREASE ? "+1" : "-1";
        connection.setVolume(change, zone);
    }
    if (command instanceof OnOffType) {
        logger.debug("handleVolumeCommand OnOffType set {} {}", zone, command);
        connection.setMute(((OnOffType) command) == OnOffType.ON, zone);
    }
}
 
Example #4
Source File: CommandExecutor.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Post PlayerControl on the device
 *
 * @param command the command is Type of Command
 */
public void postPlayerControl(Command command) {
    if (command.equals(PlayPauseType.PLAY)) {
        if (currentOperationMode == OperationModeType.STANDBY) {
            postRemoteKey(RemoteKeyType.POWER);
        } else {
            postRemoteKey(RemoteKeyType.PLAY);
        }
    } else if (command.equals(PlayPauseType.PAUSE)) {
        postRemoteKey(RemoteKeyType.PAUSE);
    } else if (command.equals(NextPreviousType.NEXT)) {
        postRemoteKey(RemoteKeyType.NEXT_TRACK);
    } else if (command.equals(NextPreviousType.PREVIOUS)) {
        postRemoteKey(RemoteKeyType.PREV_TRACK);
    }
}
 
Example #5
Source File: HeosChannelHandlerControl.java    From org.openhab.binding.heos with Eclipse Public License 1.0 6 votes vote down vote up
private void handleCommand(Command command) {
    switch (command.toString()) {
        case "PLAY":
            api.play(id);
            break;
        case "PAUSE":
            api.pause(id);
            break;
        case "NEXT":
            api.next(id);
            break;
        case "PREVIOUS":
            api.previous(id);
            break;
        case "ON":
            api.play(id);
            break;
        case "OFF":
            api.pause(id);
            break;
    }
}
 
Example #6
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public void setMute(Command command) {
    if (command != null) {
        if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
            Map<String, String> inputs = new HashMap<String, String>();
            inputs.put("Channel", "Master");

            if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
                    || command.equals(OpenClosedType.OPEN)) {
                inputs.put("DesiredMute", "True");
            } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
                    || command.equals(OpenClosedType.CLOSED)) {
                inputs.put("DesiredMute", "False");
            }

            Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetMute", inputs);

            for (String variable : result.keySet()) {
                this.onValueReceived(variable, result.get(variable), "RenderingControl");
            }
        }
    }
}
 
Example #7
Source File: AbstractTypeConverter.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object convertToBinding(Type type, HmDatapoint dp) throws ConverterException {
    if (isLoggingRequired()) {
        logAtDefaultLevel(
                "Converting type {} with value '{}' using {} to datapoint '{}' (dpType='{}', dpUnit='{}')",
                type.getClass().getSimpleName(), type.toString(), this.getClass().getSimpleName(),
                new HmDatapointInfo(dp), dp.getType(), dp.getUnit());
    }

    if (type == UnDefType.NULL) {
        return null;
    } else if (type.getClass().isEnum() && !(this instanceof OnOffTypeConverter)
            && !(this instanceof OpenClosedTypeConverter)) {
        return commandToBinding((Command) type, dp);
    } else if (!toBindingValidation(dp, type.getClass())) {
        String errorMessage = String.format("Can't convert type %s with value '%s' to %s value with %s for '%s'",
                type.getClass().getSimpleName(), type.toString(), dp.getType(), this.getClass().getSimpleName(),
                new HmDatapointInfo(dp));
        throw new ConverterTypeException(errorMessage);
    }

    return toBinding((T) type, dp);
}
 
Example #8
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Removes a range of tracks from the queue.
 * (<x,y> will remove y songs started by the song number x)
 *
 * @param command - must be in the format <startIndex, numberOfSongs>
 */
public void removeRangeOfTracksFromQueue(Command command) {
    if (command != null && command instanceof StringType) {
        Map<String, String> inputs = new HashMap<String, String>();
        String[] rangeInputSplit = command.toString().split(",");

        // If range input is incorrect, remove the first song by default
        String startIndex = rangeInputSplit[0] != null ? rangeInputSplit[0] : "1";
        String numberOfTracks = rangeInputSplit[1] != null ? rangeInputSplit[1] : "1";

        inputs.put("InstanceID", "0");
        inputs.put("StartingIndex", startIndex);
        inputs.put("NumberOfTracks", numberOfTracks);

        Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveTrackRangeFromQueue", inputs);

        for (String variable : result.keySet()) {
            this.onValueReceived(variable, result.get(variable), "AVTransport");
        }
    }
}
 
Example #9
Source File: ScriptTypeComputer.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(final QuantityLiteral assignment, ITypeComputationState state) {
    LightweightTypeReference qt = null;
    for (ITypeExpectation exp : state.getExpectations()) {
        if (exp.getExpectedType() == null) {
            continue;
        }

        if (exp.getExpectedType().isType(Number.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
        if (exp.getExpectedType().isType(State.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
        if (exp.getExpectedType().isType(Command.class)) {
            qt = getRawTypeForName(Number.class, state);
        }
    }
    if (qt == null) {
        qt = getRawTypeForName(QuantityType.class, state);
    }
    state.acceptActualType(qt);
}
 
Example #10
Source File: SrsZr5Handler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String setInputCommand(Command command) {
    switch (command.toString().toLowerCase()) {
        case "btaudio":
            return "extInput:btAudio";
        case "usb":
            return "storage:usb1";
        case "analog":
            return "extInput:line?port=1";
        case "hdmi":
            return "extInput:hdmi";
        case "network":
            return "dlna:music";
        case "cast":
            return "cast:audio";
    }
    return command.toString();
}
 
Example #11
Source File: DigitalIOThingHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (command instanceof OnOffType) {
        Integer ioChannel = Integer.valueOf(channelUID.getId().substring(channelUID.getId().length() - 1));
        if (ioChannel != null && ioChannel < ((AbstractDigitalOwDevice) sensors.get(0)).getChannelCount()) {
            Bridge bridge = getBridge();
            if (bridge != null) {
                OwBaseBridgeHandler bridgeHandler = (OwBaseBridgeHandler) bridge.getHandler();
                if (bridgeHandler != null) {
                    if (!((AbstractDigitalOwDevice) sensors.get(0)).writeChannel(bridgeHandler, ioChannel,
                            command)) {
                        logger.debug("writing to channel {} in thing {} not permitted (input channel)", channelUID,
                                this.thing.getUID());
                    }
                } else {
                    logger.warn("bridge handler not found");
                }
            } else {
                logger.warn("bridge not found");
            }
        }
    }
    super.handleCommand(channelUID, command);
}
 
Example #12
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Play a given notification sound
 *
 * @param url in the format of //host/folder/filename.mp3
 */
public void playNotificationSoundURI(Command notificationURL) {
    if (notificationURL != null && notificationURL instanceof StringType) {
        try {
            ZonePlayerHandler coordinator = getCoordinatorHandler();

            String currentURI = coordinator.getCurrentURI();

            if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)
                    || isPlayingRadio(currentURI)) {
                handleRadioStream(currentURI, notificationURL, coordinator);
            } else if (isPlayingLineIn(currentURI)) {
                handleLineIn(currentURI, notificationURL, coordinator);
            } else if (isPlayingQueue(currentURI)) {
                handleSharedQueue(notificationURL, coordinator);
            } else if (isPlaylistEmpty(coordinator)) {
                handleEmptyQueue(notificationURL, coordinator);
            }
            synchronized (notificationLock) {
                notificationLock.notify();
            }
        } catch (IllegalStateException e) {
            logger.debug("Cannot play sound ({})", e.getMessage());
        }
    }
}
 
Example #13
Source File: HtSt5000Handler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String setInputCommand(Command command) {
    switch (command.toString().toLowerCase()) {
        case "btaudio":
            return "extInput:btAudio";
        case "tv":
            return "extInput:tv";
        case "hdmi1":
            return "extInput:hdmi?port=1";
        case "hdmi2":
            return "extInput:hdmi?port=2";
        case "hdmi3":
            return "extInput:hdmi?port=3";
        case "analog":
            return "extInput:line";
        case "usb":
            return "storage:usb1";
        case "network":
            return "dlna:music";
        case "cast":
            return "cast:audio";
    }
    return command.toString();
}
 
Example #14
Source File: HttpOnlyHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
public void handleCommand(ChannelUID channelUID, Command command) {
    if (command.toString() == "REFRESH") {
        switch (channelUID.getId()) {
            case CHANNEL_ENABLE_AUDIO_ALARM:
                return;
        }
        return; // Return as we have handled the refresh command above and don't need to
                // continue further.
    } // end of "REFRESH"
    switch (channelUID.getId()) {
        case CHANNEL_THRESHOLD_AUDIO_ALARM:
            if ("ON".equals(command.toString())) {
                ipCameraHandler.audioAlarmEnabled = true;
            } else if ("OFF".equals(command.toString()) || "0".equals(command.toString())) {
                ipCameraHandler.audioAlarmEnabled = false;
            } else {
                ipCameraHandler.audioAlarmEnabled = true;
                ipCameraHandler.audioThreshold = Integer.valueOf(command.toString());
            }
            ipCameraHandler.setupFfmpegFormat("RTSPHELPER");
            return;
    }
}
 
Example #15
Source File: AstroThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (REFRESH == command) {
        logger.debug("Refreshing {}", channelUID);
        publishChannelIfLinked(channelUID);
    } else {
        logger.warn("The Astro-Binding is a read-only binding and can not handle commands");
    }
}
 
Example #16
Source File: ConnectedBluetoothHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    super.handleCommand(channelUID, command);

    // Handle REFRESH
    if (command == RefreshType.REFRESH) {
        for (BluetoothCharacteristic characteristic : deviceCharacteristics) {
            if (characteristic.getGattCharacteristic() != null
                    && channelUID.getId().equals(characteristic.getGattCharacteristic().name())) {
                device.readCharacteristic(characteristic);
                break;
            }
        }
    }
}
 
Example #17
Source File: MapTransformationProfile.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onCommandFromHandler(Command command) {
    if (function == null || sourceFormat == null) {
        logger.warn(
                "Please specify a function and a source format for this Profile in the '{}', and '{}' parameters, e.g \"translation.map\"  and \"%s\". Returning the original command now.",
                FUNCTION_PARAM, SOURCE_FORMAT_PARAM);
        callback.sendCommand(command);
        return;
    }
    callback.sendCommand((Command) transformState(command));
}
 
Example #18
Source File: ComponentLight.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Proxy method to condense all three MQTT subscriptions to one channel
 */
@Override
public void postChannelCommand(ChannelUID channelUID, Command value) {
    ChannelStateUpdateListener listener = channelStateUpdateListener;
    if (listener != null) {
        listener.postChannelCommand(colorChannel.channelUID, value);
    }
}
 
Example #19
Source File: ScriptBusEvent.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sends a command for a specified item to the event bus.
 *
 * @param itemName the name of the item to send the command to
 * @param commandString the command to send
 */
public Object sendCommand(String itemName, String commandString) {
    if (eventPublisher != null && itemRegistry != null) {
        try {
            Item item = itemRegistry.getItem(itemName);
            Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandString);
            eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, command));
        } catch (ItemNotFoundException e) {
            LoggerFactory.getLogger(ScriptBusEvent.class).warn("Item '{}' does not exist.", itemName);
        }
    }
    return null;
}
 
Example #20
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public void playPlayList(Command command) {
    if (command != null && command instanceof StringType) {
        String playlist = command.toString();
        List<SonosEntry> playlists = getPlayLists();

        SonosEntry theEntry = null;
        // search for the appropriate play list based on its name (title)
        for (SonosEntry somePlaylist : playlists) {
            if (somePlaylist.getTitle().equals(playlist)) {
                theEntry = somePlaylist;
                break;
            }
        }

        // set the URI of the group coordinator
        if (theEntry != null) {
            try {
                ZonePlayerHandler coordinator = getCoordinatorHandler();

                coordinator.addURIToQueue(theEntry);

                coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");

                String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
                if (firstTrackNumberEnqueued != null) {
                    coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
                }

                coordinator.play();
            } catch (IllegalStateException e) {
                logger.debug("Cannot play playlist ({})", e.getMessage());
            }
        } else {
            logger.debug("Playlist '{}' not found", playlist);
        }
    }
}
 
Example #21
Source File: XSLTTransformationProfile.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onCommandFromHandler(Command command) {
    if (function == null || sourceFormat == null) {
        logger.error(
                "Please specify a function and a source format for this Profile in the '{}', and '{}' parameters. Returning the original command now.",
                FUNCTION_PARAM, SOURCE_FORMAT_PARAM);
        callback.sendCommand(command);
        return;
    }
    callback.sendCommand((Command) transformState(command));
}
 
Example #22
Source File: StrDn1080Handler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleSoundSettings(Command command, ChannelUID channelUID) throws IOException {
    if (command instanceof RefreshType) {
        try {
            logger.debug("StrDn1080Handler handleSoundSettings RefreshType");
            Map<String, String> result = soundSettingsCache.getValue();

            if (result != null) {
                logger.debug("StrDn1080Handler Updateing sound field to {} {}", result.get("pureDirect"),
                        result.get("soundField"));
                if (result.get("pureDirect").equalsIgnoreCase("on")) {
                    updateState(channelUID, new StringType("pureDirect"));
                } else {
                    updateState(channelUID, new StringType(result.get("soundField")));
                }
            }
        } catch (CompletionException ex) {
            throw new IOException(ex.getCause());
        }
    }
    if (command instanceof StringType) {
        if (((StringType) command).toString().equalsIgnoreCase("pureDirect")) {
            connection.setSoundSettings("pureDirect", "on");
        } else {
            connection.setSoundSettings("soundField", ((StringType) command).toString());
        }
    }
}
 
Example #23
Source File: TradfriControllerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (command instanceof RefreshType) {
        logger.debug("Refreshing channel {}", channelUID);
        coapClient.asyncGet(this);
        return;
    }

    logger.debug("The controller is a read-only device and cannot handle commands.");
}
 
Example #24
Source File: CircuitHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    // the same handling like total metering values
    if (dssBridgeHandler != null) {
        dssBridgeHandler.handleCommand(channelUID, command);
    }
}
 
Example #25
Source File: MagicThermostatThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(@NonNull ChannelUID channelUID, @NonNull Command command) {
    if (channelUID.getId().equals(CHANNEL_SET_TEMPERATURE)) {
        if (command instanceof DecimalType || command instanceof QuantityType) {
            String state = command.toFullString() + (command instanceof DecimalType ? " °C" : "");
            scheduler.schedule(() -> {
                updateState(CHANNEL_TEMPERATURE, new QuantityType<>(state));
            }, 2, TimeUnit.SECONDS);
        }
    }
}
 
Example #26
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public void stopPlaying(Command command) {
    try {
        if (command instanceof OnOffType) {
            getCoordinatorHandler().stop();
        }
    } catch (IllegalStateException e) {
        logger.debug("Cannot handle stop command ({})", e.getMessage(), e);
    }
}
 
Example #27
Source File: AbstractMQTTThingHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (connection == null) {
        return;
    }

    final @Nullable ChannelState data = getChannelState(channelUID);

    if (data == null) {
        logger.warn("Channel {} not supported", channelUID.getId());
        if (command instanceof RefreshType) {
            updateState(channelUID.getId(), UnDefType.UNDEF);
        }
        return;
    }

    if (command instanceof RefreshType || data.isReadOnly()) {
        updateState(channelUID.getId(), data.getCache().getChannelState());
        return;
    }

    final CompletableFuture<@Nullable Void> future = data.publishValue(command);
    future.exceptionally(e -> {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage());
        return null;
    }).thenRun(() -> logger.debug("Successfully published value {} to topic {}", command, data.getStateTopic()));
}
 
Example #28
Source File: ZonePlayerHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Set the VOLUME command specific to the current grouping according to the Sonos behaviour.
 * AdHoc groups handles the volume specifically for each player.
 * Bonded groups delegate the volume to the coordinator which applies the same level to all group members.
 */
public void setVolumeForGroup(Command command) {
    if (isAdHocGroup() || isStandalonePlayer()) {
        setVolume(command);
    } else {
        try {
            getCoordinatorHandler().setVolume(command);
        } catch (IllegalStateException e) {
            logger.debug("Cannot set group volume ({})", e.getMessage());
        }
    }
}
 
Example #29
Source File: BusEvent.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sends a command for a specified item to the event bus.
 *
 * @param item the item to send the command to
 * @param command the command to send
 */
static public Object sendCommand(Item item, Command command) {
    EventPublisher publisher = ScriptServiceUtil.getEventPublisher();
    if (publisher != null && item != null) {
        publisher.post(ItemEventFactory.createCommandEvent(item.getName(), command));
    }
    return null;
}
 
Example #30
Source File: RawRockerDimmerProfile.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private synchronized void buttonPressed(Command commandToSend) {
    if (null != timeoutFuture) {
        timeoutFuture.cancel(false);
    }

    this.cancelDimmFuture();

    dimmFuture = context.getExecutorService().scheduleWithFixedDelay(() -> callback.sendCommand(commandToSend), 550,
            200, TimeUnit.MILLISECONDS);
    timeoutFuture = context.getExecutorService().schedule(() -> this.cancelDimmFuture(), 10, TimeUnit.SECONDS);
    pressedTime = System.currentTimeMillis();

}