Search in sources :

Example 16 with RefreshType

use of org.openhab.core.types.RefreshType in project openhab-addons by openhab.

the class IpCameraGroupHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (!(command instanceof RefreshType)) {
        switch(channelUID.getId()) {
            case CHANNEL_START_STREAM:
                if (OnOffType.ON.equals(command)) {
                    hlsTurnedOn = true;
                    for (IpCameraHandler handler : cameraOrder) {
                        String channelPrefix = "ipcamera:" + handler.getThing().getThingTypeUID() + ":" + handler.getThing().getUID().getId() + ":";
                        handler.handleCommand(new ChannelUID(channelPrefix + CHANNEL_START_STREAM), OnOffType.ON);
                    }
                } else {
                    // Do we turn all controls OFF, or do we remember the state before we turned them all on?
                    hlsTurnedOn = false;
                }
        }
    }
}
Also used : ChannelUID(org.openhab.core.thing.ChannelUID) RefreshType(org.openhab.core.types.RefreshType)

Example 17 with RefreshType

use of org.openhab.core.types.RefreshType in project openhab-addons by openhab.

the class IpCameraHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    if (command instanceof RefreshType) {
        switch(channelUID.getId()) {
            case CHANNEL_PAN:
                if (onvifCamera.supportsPTZ()) {
                    updateState(CHANNEL_PAN, new PercentType(Math.round(onvifCamera.getAbsolutePan())));
                }
                return;
            case CHANNEL_TILT:
                if (onvifCamera.supportsPTZ()) {
                    updateState(CHANNEL_TILT, new PercentType(Math.round(onvifCamera.getAbsoluteTilt())));
                }
                return;
            case CHANNEL_ZOOM:
                if (onvifCamera.supportsPTZ()) {
                    updateState(CHANNEL_ZOOM, new PercentType(Math.round(onvifCamera.getAbsoluteZoom())));
                }
                return;
            case CHANNEL_GOTO_PRESET:
                if (onvifCamera.supportsPTZ()) {
                    onvifCamera.sendPTZRequest(OnvifConnection.RequestType.GetPresets);
                }
                return;
        }
    } else // caution "REFRESH" can still progress to brand Handlers below the else.
    {
        switch(channelUID.getId()) {
            case CHANNEL_MP4_HISTORY_LENGTH:
                if (DecimalType.ZERO.equals(command)) {
                    mp4HistoryLength = 0;
                    mp4History = "";
                    setChannelState(CHANNEL_MP4_HISTORY, new StringType(mp4History));
                }
                return;
            case CHANNEL_GIF_HISTORY_LENGTH:
                if (DecimalType.ZERO.equals(command)) {
                    gifHistoryLength = 0;
                    gifHistory = "";
                    setChannelState(CHANNEL_GIF_HISTORY, new StringType(gifHistory));
                }
                return;
            case CHANNEL_FFMPEG_MOTION_CONTROL:
                if (OnOffType.ON.equals(command)) {
                    motionAlarmEnabled = true;
                } else if (OnOffType.OFF.equals(command) || DecimalType.ZERO.equals(command)) {
                    motionAlarmEnabled = false;
                    noMotionDetected(CHANNEL_FFMPEG_MOTION_ALARM);
                } else if (command instanceof PercentType) {
                    motionAlarmEnabled = true;
                    motionThreshold = ((PercentType) command).toBigDecimal();
                }
                setupFfmpegFormat(FFmpegFormat.RTSP_ALARMS);
                return;
            case CHANNEL_START_STREAM:
                Ffmpeg localHLS;
                if (OnOffType.ON.equals(command)) {
                    localHLS = ffmpegHLS;
                    if (localHLS == null) {
                        setupFfmpegFormat(FFmpegFormat.HLS);
                        localHLS = ffmpegHLS;
                    }
                    if (localHLS != null) {
                        // Now will run till manually stopped.
                        localHLS.setKeepAlive(-1);
                        localHLS.startConverting();
                    }
                } else {
                    localHLS = ffmpegHLS;
                    if (localHLS != null) {
                        // Still runs but will be able to auto stop when the HLS stream is no longer used.
                        localHLS.setKeepAlive(1);
                    }
                }
                return;
            case CHANNEL_EXTERNAL_MOTION:
                if (OnOffType.ON.equals(command)) {
                    motionDetected(CHANNEL_EXTERNAL_MOTION);
                } else {
                    noMotionDetected(CHANNEL_EXTERNAL_MOTION);
                }
                return;
            case CHANNEL_GOTO_PRESET:
                if (onvifCamera.supportsPTZ()) {
                    onvifCamera.gotoPreset(Integer.valueOf(command.toString()));
                }
                return;
            case CHANNEL_POLL_IMAGE:
                if (OnOffType.ON.equals(command)) {
                    if (snapshotUri.isEmpty()) {
                        ffmpegSnapshotGeneration = true;
                        setupFfmpegFormat(FFmpegFormat.SNAPSHOT);
                        updateImageChannel = false;
                    } else {
                        updateImageChannel = true;
                        // Allows this to change Image FPS on demand
                        updateSnapshot();
                    }
                } else {
                    Ffmpeg localSnaps = ffmpegSnapshot;
                    if (localSnaps != null) {
                        localSnaps.stopConverting();
                        ffmpegSnapshotGeneration = false;
                    }
                    updateImageChannel = false;
                }
                return;
            case CHANNEL_PAN:
                if (onvifCamera.supportsPTZ()) {
                    if (command instanceof IncreaseDecreaseType) {
                        if (command == IncreaseDecreaseType.INCREASE) {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveLeft);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveLeft);
                            }
                        } else {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveRight);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveRight);
                            }
                        }
                        return;
                    } else if (OnOffType.OFF.equals(command)) {
                        onvifCamera.sendPTZRequest(OnvifConnection.RequestType.Stop);
                        return;
                    }
                    onvifCamera.setAbsolutePan(Float.valueOf(command.toString()));
                    mainEventLoopGroup.schedule(this::sendPTZRequest, 500, TimeUnit.MILLISECONDS);
                }
                return;
            case CHANNEL_TILT:
                if (onvifCamera.supportsPTZ()) {
                    if (command instanceof IncreaseDecreaseType) {
                        if (IncreaseDecreaseType.INCREASE.equals(command)) {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveUp);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveUp);
                            }
                        } else {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveDown);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveDown);
                            }
                        }
                        return;
                    } else if (OnOffType.OFF.equals(command)) {
                        onvifCamera.sendPTZRequest(OnvifConnection.RequestType.Stop);
                        return;
                    }
                    onvifCamera.setAbsoluteTilt(Float.valueOf(command.toString()));
                    mainEventLoopGroup.schedule(this::sendPTZRequest, 500, TimeUnit.MILLISECONDS);
                }
                return;
            case CHANNEL_ZOOM:
                if (onvifCamera.supportsPTZ()) {
                    if (command instanceof IncreaseDecreaseType) {
                        if (IncreaseDecreaseType.INCREASE.equals(command)) {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveIn);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveIn);
                            }
                        } else {
                            if (cameraConfig.getPtzContinuous()) {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.ContinuousMoveOut);
                            } else {
                                onvifCamera.sendPTZRequest(OnvifConnection.RequestType.RelativeMoveOut);
                            }
                        }
                        return;
                    } else if (OnOffType.OFF.equals(command)) {
                        onvifCamera.sendPTZRequest(OnvifConnection.RequestType.Stop);
                        return;
                    }
                    onvifCamera.setAbsoluteZoom(Float.valueOf(command.toString()));
                    mainEventLoopGroup.schedule(this::sendPTZRequest, 500, TimeUnit.MILLISECONDS);
                }
                return;
        }
    }
    // commands and refresh now get passed to brand handlers
    switch(thing.getThingTypeUID().getId()) {
        case AMCREST_THING:
            AmcrestHandler amcrestHandler = new AmcrestHandler(getHandle());
            amcrestHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = amcrestHandler.getLowPriorityRequests();
            }
            break;
        case DAHUA_THING:
            DahuaHandler dahuaHandler = new DahuaHandler(getHandle(), cameraConfig.getNvrChannel());
            dahuaHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = dahuaHandler.getLowPriorityRequests();
            }
            break;
        case DOORBIRD_THING:
            DoorBirdHandler doorBirdHandler = new DoorBirdHandler(getHandle());
            doorBirdHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = doorBirdHandler.getLowPriorityRequests();
            }
            break;
        case HIKVISION_THING:
            HikvisionHandler hikvisionHandler = new HikvisionHandler(getHandle(), cameraConfig.getNvrChannel());
            hikvisionHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = hikvisionHandler.getLowPriorityRequests();
            }
            break;
        case FOSCAM_THING:
            FoscamHandler foscamHandler = new FoscamHandler(getHandle(), cameraConfig.getUser(), cameraConfig.getPassword());
            foscamHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = foscamHandler.getLowPriorityRequests();
            }
            break;
        case INSTAR_THING:
            InstarHandler instarHandler = new InstarHandler(getHandle());
            instarHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = instarHandler.getLowPriorityRequests();
            }
            break;
        default:
            HttpOnlyHandler defaultHandler = new HttpOnlyHandler(getHandle());
            defaultHandler.handleCommand(channelUID, command);
            if (lowPriorityRequests.isEmpty()) {
                lowPriorityRequests = defaultHandler.getLowPriorityRequests();
            }
            break;
    }
}
Also used : StringType(org.openhab.core.library.types.StringType) DoorBirdHandler(org.openhab.binding.ipcamera.internal.DoorBirdHandler) Ffmpeg(org.openhab.binding.ipcamera.internal.Ffmpeg) AmcrestHandler(org.openhab.binding.ipcamera.internal.AmcrestHandler) DahuaHandler(org.openhab.binding.ipcamera.internal.DahuaHandler) HttpOnlyHandler(org.openhab.binding.ipcamera.internal.HttpOnlyHandler) IncreaseDecreaseType(org.openhab.core.library.types.IncreaseDecreaseType) FoscamHandler(org.openhab.binding.ipcamera.internal.FoscamHandler) PercentType(org.openhab.core.library.types.PercentType) RefreshType(org.openhab.core.types.RefreshType) InstarHandler(org.openhab.binding.ipcamera.internal.InstarHandler) HikvisionHandler(org.openhab.binding.ipcamera.internal.HikvisionHandler)

Example 18 with RefreshType

use of org.openhab.core.types.RefreshType in project openhab-addons by openhab.

the class IntesisBoxHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    IntesisBoxSocketApi api = this.intesisBoxSocketApi;
    if (api != null) {
        if (!api.isConnected()) {
            logger.trace("Sending command failed, not connected");
            return;
        }
        if (command instanceof RefreshType) {
            logger.trace("Refresh channel {}", channelUID.getId());
            api.sendQuery(channelUID.getId());
            return;
        }
    }
    String value = "";
    String function = "";
    switch(channelUID.getId()) {
        case CHANNEL_TYPE_POWER:
            if (command instanceof OnOffType) {
                function = "ONOFF";
                value = command == OnOffType.ON ? "ON" : "OFF";
            }
            break;
        case CHANNEL_TYPE_TARGETTEMP:
            if (command instanceof QuantityType) {
                QuantityType<?> celsiusTemperature = (QuantityType<?>) command;
                celsiusTemperature = celsiusTemperature.toUnit(SIUnits.CELSIUS);
                if (celsiusTemperature != null) {
                    double doubleValue = celsiusTemperature.doubleValue();
                    logger.trace("targetTemp double value = {}", doubleValue);
                    doubleValue = Math.max(minTemp, Math.min(maxTemp, doubleValue));
                    value = String.format("%.0f", doubleValue * 10);
                    function = "SETPTEMP";
                    logger.trace("targetTemp raw string = {}", value);
                }
            }
            break;
        case CHANNEL_TYPE_MODE:
            function = "MODE";
            value = command.toString();
            break;
        case CHANNEL_TYPE_FANSPEED:
            function = "FANSP";
            value = command.toString();
            break;
        case CHANNEL_TYPE_VANESUD:
            function = "VANEUD";
            value = command.toString();
            break;
        case CHANNEL_TYPE_VANESLR:
            function = "VANELR";
            value = command.toString();
            break;
    }
    if (!value.isEmpty() || function.isEmpty()) {
        if (api != null) {
            logger.trace("Sending command {} to function {}", value, function);
            api.sendCommand(function, value);
        } else {
            logger.warn("Sending command failed, could not get API");
        }
    }
}
Also used : OnOffType(org.openhab.core.library.types.OnOffType) QuantityType(org.openhab.core.library.types.QuantityType) IntesisBoxSocketApi(org.openhab.binding.intesis.internal.api.IntesisBoxSocketApi) RefreshType(org.openhab.core.types.RefreshType)

Example 19 with RefreshType

use of org.openhab.core.types.RefreshType in project openhab-addons by openhab.

the class EchoHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    try {
        logger.trace("Command '{}' received for channel '{}'", command, channelUID);
        int waitForUpdate = 1000;
        boolean needBluetoothRefresh = false;
        String lastKnownBluetoothMAC = this.lastKnownBluetoothMAC;
        ScheduledFuture<?> updateStateJob = this.updateStateJob;
        this.updateStateJob = null;
        if (updateStateJob != null) {
            this.disableUpdate = false;
            updateStateJob.cancel(false);
        }
        AccountHandler account = this.account;
        if (account == null) {
            return;
        }
        Connection connection = account.findConnection();
        if (connection == null) {
            return;
        }
        Device device = this.device;
        if (device == null) {
            return;
        }
        String channelId = channelUID.getId();
        for (ChannelHandler channelHandler : channelHandlers) {
            if (channelHandler.tryHandleCommand(device, connection, channelId, command)) {
                return;
            }
        }
        // Player commands
        if (channelId.equals(CHANNEL_PLAYER)) {
            if (command == PlayPauseType.PAUSE || command == OnOffType.OFF) {
                connection.command(device, "{\"type\":\"PauseCommand\"}");
            } else if (command == PlayPauseType.PLAY || command == OnOffType.ON) {
                if (isPaused) {
                    connection.command(device, "{\"type\":\"PlayCommand\"}");
                } else {
                    connection.playMusicVoiceCommand(device, this.musicProviderId, "!");
                    waitForUpdate = 3000;
                }
            } else if (command == NextPreviousType.NEXT) {
                connection.command(device, "{\"type\":\"NextCommand\"}");
            } else if (command == NextPreviousType.PREVIOUS) {
                connection.command(device, "{\"type\":\"PreviousCommand\"}");
            } else if (command == RewindFastforwardType.FASTFORWARD) {
                connection.command(device, "{\"type\":\"ForwardCommand\"}");
            } else if (command == RewindFastforwardType.REWIND) {
                connection.command(device, "{\"type\":\"RewindCommand\"}");
            }
        }
        // Notification commands
        if (channelId.equals(CHANNEL_NOTIFICATION_VOLUME)) {
            if (command instanceof PercentType) {
                int volume = ((PercentType) command).intValue();
                connection.notificationVolume(device, volume);
                this.notificationVolumeLevel = volume;
                waitForUpdate = -1;
                account.forceCheckData();
            }
        }
        if (channelId.equals(CHANNEL_ASCENDING_ALARM)) {
            if (command == OnOffType.OFF) {
                connection.ascendingAlarm(device, false);
                this.ascendingAlarm = false;
                waitForUpdate = -1;
                account.forceCheckData();
            }
            if (command == OnOffType.ON) {
                connection.ascendingAlarm(device, true);
                this.ascendingAlarm = true;
                waitForUpdate = -1;
                account.forceCheckData();
            }
        }
        // Media progress commands
        Long mediaPosition = null;
        if (channelId.equals(CHANNEL_MEDIA_PROGRESS)) {
            if (command instanceof PercentType) {
                PercentType value = (PercentType) command;
                int percent = value.intValue();
                mediaPosition = Math.round((mediaLengthMs / 1000d) * (percent / 100d));
            }
        }
        if (channelId.equals(CHANNEL_MEDIA_PROGRESS_TIME)) {
            if (command instanceof DecimalType) {
                DecimalType value = (DecimalType) command;
                mediaPosition = value.longValue();
            }
            if (command instanceof QuantityType<?>) {
                QuantityType<?> value = (QuantityType<?>) command;
                @Nullable QuantityType<?> seconds = value.toUnit(Units.SECOND);
                if (seconds != null) {
                    mediaPosition = seconds.longValue();
                }
            }
        }
        if (mediaPosition != null) {
            waitForUpdate = -1;
            synchronized (progressLock) {
                String seekCommand = "{\"type\":\"SeekCommand\",\"mediaPosition\":" + mediaPosition + ",\"contentFocusClientId\":null}";
                connection.command(device, seekCommand);
                // Must be sent twice, the first one is ignored sometimes
                connection.command(device, seekCommand);
                this.mediaProgressMs = mediaPosition * 1000;
                mediaStartMs = System.currentTimeMillis() - this.mediaProgressMs;
                updateMediaProgress(false);
            }
        }
        // Volume commands
        if (channelId.equals(CHANNEL_VOLUME)) {
            Integer volume = null;
            if (command instanceof PercentType) {
                PercentType value = (PercentType) command;
                volume = value.intValue();
            } else if (command == OnOffType.OFF) {
                volume = 0;
            } else if (command == OnOffType.ON) {
                volume = lastKnownVolume;
            } else if (command == IncreaseDecreaseType.INCREASE) {
                if (lastKnownVolume < 100) {
                    lastKnownVolume++;
                    volume = lastKnownVolume;
                }
            } else if (command == IncreaseDecreaseType.DECREASE) {
                if (lastKnownVolume > 0) {
                    lastKnownVolume--;
                    volume = lastKnownVolume;
                }
            }
            if (volume != null) {
                if ("WHA".equals(device.deviceFamily)) {
                    connection.command(device, "{\"type\":\"VolumeLevelCommand\",\"volumeLevel\":" + volume + ",\"contentFocusClientId\":\"Default\"}");
                } else {
                    connection.volume(device, volume);
                }
                lastKnownVolume = volume;
                updateState(CHANNEL_VOLUME, new PercentType(lastKnownVolume));
                waitForUpdate = -1;
            }
        }
        // equalizer commands
        if (channelId.equals(CHANNEL_EQUALIZER_BASS) || channelId.equals(CHANNEL_EQUALIZER_MIDRANGE) || channelId.equals(CHANNEL_EQUALIZER_TREBLE)) {
            if (handleEqualizerCommands(channelId, command, connection, device)) {
                waitForUpdate = -1;
            }
        }
        // shuffle command
        if (channelId.equals(CHANNEL_SHUFFLE)) {
            if (command instanceof OnOffType) {
                OnOffType value = (OnOffType) command;
                connection.command(device, "{\"type\":\"ShuffleCommand\",\"shuffle\":\"" + (value == OnOffType.ON ? "true" : "false") + "\"}");
            }
        }
        // play music command
        if (channelId.equals(CHANNEL_MUSIC_PROVIDER_ID)) {
            if (command instanceof StringType) {
                waitForUpdate = 0;
                String musicProviderId = command.toFullString();
                if (!musicProviderId.equals(this.musicProviderId)) {
                    this.musicProviderId = musicProviderId;
                    if (this.isPlaying) {
                        connection.playMusicVoiceCommand(device, this.musicProviderId, "!");
                        waitForUpdate = 3000;
                    }
                }
            }
        }
        if (channelId.equals(CHANNEL_PLAY_MUSIC_VOICE_COMMAND)) {
            if (command instanceof StringType) {
                String voiceCommand = command.toFullString();
                if (!this.musicProviderId.isEmpty()) {
                    connection.playMusicVoiceCommand(device, this.musicProviderId, voiceCommand);
                    waitForUpdate = 3000;
                    updatePlayMusicVoiceCommand = true;
                }
            }
        }
        // bluetooth commands
        if (channelId.equals(CHANNEL_BLUETOOTH_MAC)) {
            needBluetoothRefresh = true;
            if (command instanceof StringType) {
                String address = ((StringType) command).toFullString();
                if (!address.isEmpty()) {
                    waitForUpdate = 4000;
                }
                connection.bluetooth(device, address);
            }
        }
        if (channelId.equals(CHANNEL_BLUETOOTH)) {
            needBluetoothRefresh = true;
            if (command == OnOffType.ON) {
                waitForUpdate = 4000;
                String bluetoothId = lastKnownBluetoothMAC;
                BluetoothState state = bluetoothState;
                if (state != null && (bluetoothId == null || bluetoothId.isEmpty())) {
                    for (PairedDevice paired : state.getPairedDeviceList()) {
                        String pairedAddress = paired.address;
                        if (pairedAddress != null && !pairedAddress.isEmpty()) {
                            lastKnownBluetoothMAC = pairedAddress;
                            break;
                        }
                    }
                }
                if (lastKnownBluetoothMAC != null && !lastKnownBluetoothMAC.isEmpty()) {
                    connection.bluetooth(device, lastKnownBluetoothMAC);
                }
            } else if (command == OnOffType.OFF) {
                connection.bluetooth(device, null);
            }
        }
        if (channelId.equals(CHANNEL_BLUETOOTH_DEVICE_NAME)) {
            needBluetoothRefresh = true;
        }
        // amazon music commands
        if (channelId.equals(CHANNEL_AMAZON_MUSIC_TRACK_ID)) {
            if (command instanceof StringType) {
                String trackId = command.toFullString();
                if (!trackId.isEmpty()) {
                    waitForUpdate = 3000;
                }
                connection.playAmazonMusicTrack(device, trackId);
            }
        }
        if (channelId.equals(CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID)) {
            if (command instanceof StringType) {
                String playListId = command.toFullString();
                if (!playListId.isEmpty()) {
                    waitForUpdate = 3000;
                }
                connection.playAmazonMusicPlayList(device, playListId);
            }
        }
        if (channelId.equals(CHANNEL_AMAZON_MUSIC)) {
            if (command == OnOffType.ON) {
                String lastKnownAmazonMusicId = this.lastKnownAmazonMusicId;
                if (lastKnownAmazonMusicId != null && !lastKnownAmazonMusicId.isEmpty()) {
                    waitForUpdate = 3000;
                }
                connection.playAmazonMusicTrack(device, lastKnownAmazonMusicId);
            } else if (command == OnOffType.OFF) {
                connection.playAmazonMusicTrack(device, "");
            }
        }
        // radio commands
        if (channelId.equals(CHANNEL_RADIO_STATION_ID)) {
            if (command instanceof StringType) {
                String stationId = command.toFullString();
                if (!stationId.isEmpty()) {
                    waitForUpdate = 3000;
                }
                connection.playRadio(device, stationId);
            }
        }
        if (channelId.equals(CHANNEL_RADIO)) {
            if (command == OnOffType.ON) {
                String lastKnownRadioStationId = this.lastKnownRadioStationId;
                if (lastKnownRadioStationId != null && !lastKnownRadioStationId.isEmpty()) {
                    waitForUpdate = 3000;
                }
                connection.playRadio(device, lastKnownRadioStationId);
            } else if (command == OnOffType.OFF) {
                connection.playRadio(device, "");
            }
        }
        // notification
        if (channelId.equals(CHANNEL_REMIND)) {
            if (command instanceof StringType) {
                stopCurrentNotification();
                String reminder = command.toFullString();
                if (!reminder.isEmpty()) {
                    waitForUpdate = 3000;
                    updateRemind = true;
                    currentNotification = connection.notification(device, "Reminder", reminder, null);
                    currentNotifcationUpdateTimer = scheduler.scheduleWithFixedDelay(() -> {
                        updateNotificationTimerState();
                    }, 1, 1, TimeUnit.SECONDS);
                }
            }
        }
        if (channelId.equals(CHANNEL_PLAY_ALARM_SOUND)) {
            if (command instanceof StringType) {
                stopCurrentNotification();
                String alarmSound = command.toFullString();
                if (!alarmSound.isEmpty()) {
                    waitForUpdate = 3000;
                    updateAlarm = true;
                    String[] parts = alarmSound.split(":", 2);
                    JsonNotificationSound sound = new JsonNotificationSound();
                    if (parts.length == 2) {
                        sound.providerId = parts[0];
                        sound.id = parts[1];
                    } else {
                        sound.providerId = "ECHO";
                        sound.id = alarmSound;
                    }
                    currentNotification = connection.notification(device, "Alarm", null, sound);
                    currentNotifcationUpdateTimer = scheduler.scheduleWithFixedDelay(() -> {
                        updateNotificationTimerState();
                    }, 1, 1, TimeUnit.SECONDS);
                }
            }
        }
        // routine commands
        if (channelId.equals(CHANNEL_TEXT_TO_SPEECH)) {
            if (command instanceof StringType) {
                String text = command.toFullString();
                if (!text.isEmpty()) {
                    waitForUpdate = 1000;
                    updateTextToSpeech = true;
                    startTextToSpeech(connection, device, text);
                }
            }
        }
        if (channelId.equals(CHANNEL_TEXT_TO_SPEECH_VOLUME)) {
            if (command instanceof PercentType) {
                PercentType value = (PercentType) command;
                textToSpeechVolume = value.intValue();
            } else if (command == OnOffType.OFF) {
                textToSpeechVolume = 0;
            } else if (command == OnOffType.ON) {
                textToSpeechVolume = lastKnownVolume;
            } else if (command == IncreaseDecreaseType.INCREASE) {
                if (textToSpeechVolume < 100) {
                    textToSpeechVolume++;
                }
            } else if (command == IncreaseDecreaseType.DECREASE) {
                if (textToSpeechVolume > 0) {
                    textToSpeechVolume--;
                }
            }
            this.updateState(channelId, new PercentType(textToSpeechVolume));
        }
        if (channelId.equals(CHANNEL_TEXT_COMMAND)) {
            if (command instanceof StringType) {
                String text = command.toFullString();
                if (!text.isEmpty()) {
                    waitForUpdate = 1000;
                    updateTextCommand = true;
                    startTextCommand(connection, device, text);
                }
            }
        }
        if (channelId.equals(CHANNEL_LAST_VOICE_COMMAND)) {
            if (command instanceof StringType) {
                String text = command.toFullString();
                if (!text.isEmpty()) {
                    waitForUpdate = -1;
                    startTextToSpeech(connection, device, text);
                }
            }
        }
        if (channelId.equals(CHANNEL_START_COMMAND)) {
            if (command instanceof StringType) {
                String commandText = command.toFullString();
                if (!commandText.isEmpty()) {
                    updateStartCommand = true;
                    if (commandText.startsWith(FLASH_BRIEFING_COMMAND_PREFIX)) {
                        // Handle custom flashbriefings commands
                        String flashBriefingId = commandText.substring(FLASH_BRIEFING_COMMAND_PREFIX.length());
                        for (FlashBriefingProfileHandler flashBriefingHandler : account.getFlashBriefingProfileHandlers()) {
                            ThingUID flashBriefingUid = flashBriefingHandler.getThing().getUID();
                            if (flashBriefingId.equals(flashBriefingHandler.getThing().getUID().getId())) {
                                flashBriefingHandler.handleCommand(new ChannelUID(flashBriefingUid, CHANNEL_PLAY_ON_DEVICE), new StringType(device.serialNumber));
                                break;
                            }
                        }
                    } else {
                        // Handle standard commands
                        if (!commandText.startsWith("Alexa.")) {
                            commandText = "Alexa." + commandText + ".Play";
                        }
                        waitForUpdate = 1000;
                        connection.executeSequenceCommand(device, commandText, Map.of());
                    }
                }
            }
        }
        if (channelId.equals(CHANNEL_START_ROUTINE)) {
            if (command instanceof StringType) {
                String utterance = command.toFullString();
                if (!utterance.isEmpty()) {
                    waitForUpdate = 1000;
                    updateRoutine = true;
                    connection.startRoutine(device, utterance);
                }
            }
        }
        if (waitForUpdate < 0) {
            return;
        }
        // force update of the state
        this.disableUpdate = true;
        final boolean bluetoothRefresh = needBluetoothRefresh;
        Runnable doRefresh = () -> {
            this.disableUpdate = false;
            BluetoothState state = null;
            if (bluetoothRefresh) {
                JsonBluetoothStates states;
                states = connection.getBluetoothConnectionStates();
                if (states != null) {
                    state = states.findStateByDevice(device);
                }
            }
            updateState(account, device, state, null, null, null, null, null);
        };
        if (command instanceof RefreshType) {
            waitForUpdate = 0;
            account.forceCheckData();
        }
        if (waitForUpdate == 0) {
            doRefresh.run();
        } else {
            this.updateStateJob = scheduler.schedule(doRefresh, waitForUpdate, TimeUnit.MILLISECONDS);
        }
    } catch (IOException | URISyntaxException | InterruptedException e) {
        logger.info("handleCommand fails", e);
    }
}
Also used : StringType(org.openhab.core.library.types.StringType) JsonBluetoothStates(org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates) ChannelHandler(org.openhab.binding.amazonechocontrol.internal.channelhandler.ChannelHandler) URISyntaxException(java.net.URISyntaxException) PairedDevice(org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice) ChannelUID(org.openhab.core.thing.ChannelUID) JsonNotificationSound(org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound) PairedDevice(org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice) Device(org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device) Connection(org.openhab.binding.amazonechocontrol.internal.Connection) PercentType(org.openhab.core.library.types.PercentType) BluetoothState(org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState) IOException(java.io.IOException) RefreshType(org.openhab.core.types.RefreshType) QuantityType(org.openhab.core.library.types.QuantityType) OnOffType(org.openhab.core.library.types.OnOffType) ThingUID(org.openhab.core.thing.ThingUID) DecimalType(org.openhab.core.library.types.DecimalType) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 20 with RefreshType

use of org.openhab.core.types.RefreshType in project openhab-addons by openhab.

the class FlashBriefingProfileHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    AccountHandler accountHandler = this.accountHandler;
    if (accountHandler == null) {
        return;
    }
    int waitForUpdate = -1;
    ScheduledFuture<?> updateStateJob = this.updateStateJob;
    this.updateStateJob = null;
    if (updateStateJob != null) {
        updateStateJob.cancel(false);
    }
    String channelId = channelUID.getId();
    if (command instanceof RefreshType) {
        waitForUpdate = 0;
    }
    if (channelId.equals(CHANNEL_SAVE)) {
        if (command.equals(OnOffType.ON)) {
            saveCurrentProfile(accountHandler);
            waitForUpdate = 500;
        }
    }
    if (channelId.equals(CHANNEL_ACTIVE)) {
        if (command.equals(OnOffType.ON)) {
            String currentConfigurationJson = this.currentConfigurationJson;
            if (!currentConfigurationJson.isEmpty()) {
                accountHandler.setEnabledFlashBriefingsJson(currentConfigurationJson);
                updateState(CHANNEL_ACTIVE, OnOffType.ON);
                waitForUpdate = 500;
            }
        }
    }
    if (channelId.equals(CHANNEL_PLAY_ON_DEVICE)) {
        if (command instanceof StringType) {
            String deviceSerialOrName = command.toFullString();
            String currentConfigurationJson = this.currentConfigurationJson;
            if (!currentConfigurationJson.isEmpty()) {
                String old = accountHandler.getEnabledFlashBriefingsJson();
                accountHandler.setEnabledFlashBriefingsJson(currentConfigurationJson);
                Device device = accountHandler.findDeviceJsonBySerialOrName(deviceSerialOrName);
                if (device == null) {
                    logger.warn("Device '{}' not found", deviceSerialOrName);
                } else {
                    @Nullable Connection connection = accountHandler.findConnection();
                    if (connection == null) {
                        logger.warn("Connection for '{}' not found", accountHandler.getThing().getUID().getId());
                    } else {
                        connection.executeSequenceCommand(device, "Alexa.FlashBriefing.Play", Map.of());
                        scheduler.schedule(() -> accountHandler.setEnabledFlashBriefingsJson(old), 1000, TimeUnit.MILLISECONDS);
                        updateState(CHANNEL_ACTIVE, OnOffType.ON);
                    }
                }
                updatePlayOnDevice = true;
                waitForUpdate = 1000;
            }
        }
    }
    if (waitForUpdate >= 0) {
        this.updateStateJob = scheduler.schedule(() -> accountHandler.updateFlashBriefingHandlers(), waitForUpdate, TimeUnit.MILLISECONDS);
    }
}
Also used : StringType(org.openhab.core.library.types.StringType) Device(org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device) Connection(org.openhab.binding.amazonechocontrol.internal.Connection) RefreshType(org.openhab.core.types.RefreshType) Nullable(org.eclipse.jdt.annotation.Nullable)

Aggregations

RefreshType (org.openhab.core.types.RefreshType)210 OnOffType (org.openhab.core.library.types.OnOffType)81 StringType (org.openhab.core.library.types.StringType)66 DecimalType (org.openhab.core.library.types.DecimalType)60 PercentType (org.openhab.core.library.types.PercentType)50 QuantityType (org.openhab.core.library.types.QuantityType)29 Channel (org.openhab.core.thing.Channel)26 State (org.openhab.core.types.State)26 IncreaseDecreaseType (org.openhab.core.library.types.IncreaseDecreaseType)25 IOException (java.io.IOException)22 Nullable (org.eclipse.jdt.annotation.Nullable)18 Bridge (org.openhab.core.thing.Bridge)18 ChannelUID (org.openhab.core.thing.ChannelUID)16 HSBType (org.openhab.core.library.types.HSBType)15 BigDecimal (java.math.BigDecimal)14 DateTimeType (org.openhab.core.library.types.DateTimeType)11 UpDownType (org.openhab.core.library.types.UpDownType)11 Temperature (javax.measure.quantity.Temperature)8 Thing (org.openhab.core.thing.Thing)8 Command (org.openhab.core.types.Command)8