2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.kaleidescape.internal.handler;
15 import static org.openhab.binding.kaleidescape.internal.KaleidescapeBindingConstants.*;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.HashSet;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import javax.measure.Unit;
28 import javax.measure.quantity.Time;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.kaleidescape.internal.KaleidescapeException;
34 import org.openhab.binding.kaleidescape.internal.KaleidescapeThingActions;
35 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeConnector;
36 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeDefaultConnector;
37 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeIpConnector;
38 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeMessageEvent;
39 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeMessageEventListener;
40 import org.openhab.binding.kaleidescape.internal.communication.KaleidescapeSerialConnector;
41 import org.openhab.binding.kaleidescape.internal.configuration.KaleidescapeThingConfiguration;
42 import org.openhab.core.io.transport.serial.SerialPortManager;
43 import org.openhab.core.library.types.NextPreviousType;
44 import org.openhab.core.library.types.OnOffType;
45 import org.openhab.core.library.types.PercentType;
46 import org.openhab.core.library.types.PlayPauseType;
47 import org.openhab.core.library.types.RewindFastforwardType;
48 import org.openhab.core.library.types.StringType;
49 import org.openhab.core.library.unit.Units;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.ThingTypeUID;
55 import org.openhab.core.thing.binding.BaseThingHandler;
56 import org.openhab.core.thing.binding.ThingHandlerService;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.RefreshType;
59 import org.openhab.core.types.State;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * The {@link KaleidescapeHandler} is responsible for handling commands, which are sent to one of the channels.
66 * Based on the Rotel binding by Laurent Garnier
68 * @author Michael Lobstein - Initial contribution
71 public class KaleidescapeHandler extends BaseThingHandler implements KaleidescapeMessageEventListener {
72 private static final long RECON_POLLING_INTERVAL_S = 60;
73 private static final long POLLING_INTERVAL_S = 20;
75 private final Logger logger = LoggerFactory.getLogger(KaleidescapeHandler.class);
76 private final SerialPortManager serialPortManager;
77 private final Map<String, String> cache = new HashMap<String, String>();
79 protected final HttpClient httpClient;
80 protected final Unit<Time> apiSecondUnit = Units.SECOND;
82 private ThingTypeUID thingTypeUID = THING_TYPE_PLAYER;
83 private @Nullable ScheduledFuture<?> reconnectJob;
84 private @Nullable ScheduledFuture<?> pollingJob;
85 private long lastEventReceived = 0;
86 private int updatePeriod = 0;
88 protected KaleidescapeConnector connector = new KaleidescapeDefaultConnector();
89 protected int metaRuntimeMultiple = 1;
90 protected int volume = 0;
91 protected boolean volumeEnabled = false;
92 protected boolean isMuted = false;
93 protected boolean isLoadHighlightedDetails = false;
94 protected boolean isLoadAlbumDetails = false;
95 protected String friendlyName = EMPTY;
96 protected Object sequenceLock = new Object();
98 public KaleidescapeHandler(Thing thing, SerialPortManager serialPortManager, HttpClient httpClient) {
100 this.serialPortManager = serialPortManager;
101 this.httpClient = httpClient;
104 protected void updateChannel(String channelUID, State state) {
105 this.updateState(channelUID, state);
108 protected void updateDetailChannel(String channelUID, State state) {
109 this.updateState(DETAIL + channelUID, state);
112 protected void updateThingProperty(String name, String value) {
113 thing.setProperty(name, value);
117 public void initialize() {
118 final String uid = this.getThing().getUID().getAsString();
119 KaleidescapeThingConfiguration config = getConfigAs(KaleidescapeThingConfiguration.class);
121 this.thingTypeUID = thing.getThingTypeUID();
123 // Check configuration settings
124 String configError = null;
125 final String serialPort = config.serialPort;
126 final String host = config.host;
127 final Integer port = config.port;
128 final Integer updatePeriod = config.updatePeriod;
129 this.isLoadHighlightedDetails = config.loadHighlightedDetails;
130 this.isLoadAlbumDetails = config.loadAlbumDetails;
132 if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
133 configError = "undefined serialPort and host configuration settings; please set one of them";
134 } else if (host == null || host.isEmpty()) {
135 if (serialPort != null && serialPort.toLowerCase().startsWith("rfc2217")) {
136 configError = "use host and port configuration settings for a serial over IP connection";
140 configError = "undefined port configuration setting";
141 } else if (port <= 0) {
142 configError = "invalid port configuration setting";
146 if (configError != null) {
147 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
151 if (updatePeriod != null) {
152 this.updatePeriod = updatePeriod;
155 // check if volume is enabled
156 if (config.volumeEnabled) {
157 this.volumeEnabled = true;
158 this.volume = config.initialVolume;
159 this.updateState(VOLUME, new PercentType(this.volume));
160 this.updateState(MUTE, OnOffType.OFF);
163 if (serialPort != null) {
164 connector = new KaleidescapeSerialConnector(serialPortManager, serialPort, uid);
165 } else if (port != null) {
166 connector = new KaleidescapeIpConnector(host, port, uid);
168 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
169 "Either Serial port or Host & Port must be specifed");
173 updateStatus(ThingStatus.UNKNOWN);
175 scheduleReconnectJob();
176 schedulePollingJob();
180 public void dispose() {
181 cancelReconnectJob();
187 public Collection<Class<? extends ThingHandlerService>> getServices() {
188 return Collections.singletonList(KaleidescapeThingActions.class);
191 public void handleRawCommand(@Nullable String command) {
192 synchronized (sequenceLock) {
194 connector.sendCommand(command);
195 } catch (KaleidescapeException e) {
196 logger.warn("K Command: {} failed", command);
202 public void handleCommand(ChannelUID channelUID, Command command) {
203 String channel = channelUID.getId();
205 if (getThing().getStatus() != ThingStatus.ONLINE) {
206 logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
209 synchronized (sequenceLock) {
210 if (!connector.isConnected()) {
211 logger.debug("Command {} from channel {} is ignored: connection not established", command, channel);
216 if (command instanceof RefreshType) {
217 handleRefresh(channel);
223 if (command instanceof OnOffType) {
224 connector.sendCommand(command == OnOffType.ON ? LEAVE_STANDBY : ENTER_STANDBY);
228 if (command instanceof PercentType) {
229 this.volume = (int) ((PercentType) command).doubleValue();
230 logger.debug("Got volume command {}", this.volume);
231 connector.sendCommand(SEND_EVENT_VOLUME_LEVEL_EQ + this.volume);
235 if (command instanceof OnOffType) {
236 this.isMuted = command == OnOffType.ON ? true : false;
238 connector.sendCommand(SEND_EVENT_MUTE + (this.isMuted ? MUTE_ON : MUTE_OFF));
241 if (command instanceof OnOffType) {
242 connector.sendCommand(command == OnOffType.ON ? MUSIC_REPEAT_ON : MUSIC_REPEAT_OFF);
246 if (command instanceof OnOffType) {
247 connector.sendCommand(command == OnOffType.ON ? MUSIC_RANDOM_ON : MUSIC_RANDOM_OFF);
252 handleControlCommand(command);
255 logger.debug("Command {} from channel {} failed: unexpected command", command, channel);
258 } catch (KaleidescapeException e) {
259 logger.debug("Command {} from channel {} failed: {}", command, channel, e.getMessage());
260 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
262 scheduleReconnectJob();
268 * Open the connection with the Kaleidescape component
270 * @return true if the connection is opened successfully or false if not
272 private synchronized boolean openConnection() {
273 connector.addEventListener(this);
276 } catch (KaleidescapeException e) {
277 logger.debug("openConnection() failed: {}", e.getMessage());
279 logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
280 return connector.isConnected();
284 * Close the connection with the Kaleidescape component
286 private synchronized void closeConnection() {
287 if (connector.isConnected()) {
289 connector.removeEventListener(this);
290 logger.debug("closeConnection(): disconnected");
295 public void onNewMessageEvent(KaleidescapeMessageEvent evt) {
296 lastEventReceived = System.currentTimeMillis();
298 // check if we are in standby
299 if (STANDBY_MSG.equals(evt.getKey())) {
300 if (!ThingStatusDetail.BRIDGE_OFFLINE.equals(thing.getStatusInfo().getStatusDetail())) {
301 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.BRIDGE_OFFLINE, STANDBY_MSG);
306 // Use the Enum valueOf to handle the message based on the event key. Otherwise there would be a huge
307 // case statement here
308 KaleidescapeMessageHandler.valueOf(evt.getKey()).handleMessage(evt.getValue(), this);
310 if (!evt.isCached()) {
311 cache.put(evt.getKey(), evt.getValue());
314 if (ThingStatusDetail.BRIDGE_OFFLINE.equals(thing.getStatusInfo().getStatusDetail())) {
315 // no longer in standby, update the status
316 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.friendlyName);
318 } catch (IllegalArgumentException e) {
319 logger.debug("Unhandled message: key {} = {}", evt.getKey(), evt.getValue());
324 * Schedule the reconnection job
326 private void scheduleReconnectJob() {
327 logger.debug("Schedule reconnect job");
328 cancelReconnectJob();
329 reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
330 synchronized (sequenceLock) {
331 if (!connector.isConnected()) {
332 logger.debug("Trying to reconnect...");
334 String error = EMPTY;
335 if (openConnection()) {
338 Set<String> initialCommands = new HashSet<>(Arrays.asList(GET_DEVICE_TYPE_NAME,
339 GET_FRIENDLY_NAME, GET_DEVICE_INFO, GET_SYSTEM_VERSION, GET_DEVICE_POWER_STATE,
340 GET_CINEMASCAPE_MASK, GET_CINEMASCAPE_MODE, GET_SCALE_MODE, GET_SCREEN_MASK,
341 GET_SCREEN_MASK2, GET_VIDEO_MODE, GET_UI_STATE, GET_HIGHLIGHTED_SELECTION,
342 GET_CHILD_MODE_STATE, GET_PLAY_STATUS, GET_MOVIE_LOCATION, GET_MOVIE_MEDIA_TYPE,
343 GET_PLAYING_TITLE_NAME));
345 // Premiere Players and Cinema One support music
346 if (thingTypeUID.equals(THING_TYPE_PLAYER) || thingTypeUID.equals(THING_TYPE_CINEMA_ONE)) {
347 initialCommands.addAll(Arrays.asList(GET_MUSIC_NOW_PLAYING_STATUS,
348 GET_MUSIC_PLAY_STATUS, GET_MUSIC_TITLE));
351 // everything after Premiere Player supports GET_SYSTEM_READINESS_STATE
352 if (!thingTypeUID.equals(THING_TYPE_PLAYER)) {
353 initialCommands.add(GET_SYSTEM_READINESS_STATE);
356 // only Strato supports the GET_*_COLOR commands
357 if (thingTypeUID.equals(THING_TYPE_STRATO)) {
358 initialCommands.addAll(Arrays.asList(GET_VIDEO_COLOR, GET_CONTENT_COLOR));
361 initialCommands.forEach(command -> {
363 connector.sendCommand(command);
364 } catch (KaleidescapeException e) {
365 logger.debug("{}: {}", "Error sending initial commands", e.getMessage());
369 if (this.updatePeriod == 1) {
370 connector.sendCommand(SET_STATUS_CUE_PERIOD_1);
372 } catch (KaleidescapeException e) {
373 error = "First command after connection failed";
374 logger.debug("{}: {}", error, e.getMessage());
378 error = "Reconnection failed";
380 if (!error.equals(EMPTY)) {
381 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error);
384 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.friendlyName);
385 lastEventReceived = System.currentTimeMillis();
388 }, 1, RECON_POLLING_INTERVAL_S, TimeUnit.SECONDS);
392 * Cancel the reconnection job
394 private void cancelReconnectJob() {
395 ScheduledFuture<?> reconnectJob = this.reconnectJob;
396 if (reconnectJob != null) {
397 reconnectJob.cancel(true);
398 this.reconnectJob = null;
403 * Schedule the polling job
405 private void schedulePollingJob() {
406 logger.debug("Schedule polling job");
409 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
410 synchronized (sequenceLock) {
411 if (connector.isConnected()) {
412 logger.debug("Polling the component for updated status...");
416 } catch (KaleidescapeException e) {
417 logger.debug("Polling error: {}", e.getMessage());
420 // if the last successful polling update was more than 1.25 intervals ago,
421 // the component is not responding even though the connection is still good
422 if ((System.currentTimeMillis() - lastEventReceived) > (POLLING_INTERVAL_S * 1.25 * 1000)) {
423 logger.warn("Component not responding to status requests");
424 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
425 "Component not responding to status requests");
427 scheduleReconnectJob();
431 }, POLLING_INTERVAL_S, POLLING_INTERVAL_S, TimeUnit.SECONDS);
435 * Cancel the polling job
437 private void cancelPollingJob() {
438 ScheduledFuture<?> pollingJob = this.pollingJob;
439 if (pollingJob != null) {
440 pollingJob.cancel(true);
441 this.pollingJob = null;
445 private void handleControlCommand(Command command) throws KaleidescapeException {
446 if (command instanceof PlayPauseType) {
447 if (command == PlayPauseType.PLAY) {
448 connector.sendCommand(PLAY);
449 } else if (command == PlayPauseType.PAUSE) {
450 connector.sendCommand(PAUSE);
452 } else if (command instanceof NextPreviousType) {
453 if (command == NextPreviousType.NEXT) {
454 connector.sendCommand(NEXT);
455 } else if (command == NextPreviousType.PREVIOUS) {
456 connector.sendCommand(PREVIOUS);
458 } else if (command instanceof RewindFastforwardType) {
459 if (command == RewindFastforwardType.FASTFORWARD) {
460 connector.sendCommand(SCAN_FORWARD);
461 } else if (command == RewindFastforwardType.REWIND) {
462 connector.sendCommand(SCAN_REVERSE);
465 logger.warn("Unknown control command: {}", command);
469 private void handleRefresh(String channel) throws KaleidescapeException {
472 connector.sendCommand(GET_DEVICE_POWER_STATE, cache.get("DEVICE_POWER_STATE"));
475 updateState(channel, new PercentType(this.volume));
478 updateState(channel, this.isMuted ? OnOffType.ON : OnOffType.OFF);
481 connector.sendCommand(GET_PLAYING_TITLE_NAME, cache.get("TITLE_NAME"));
491 connector.sendCommand(GET_PLAY_STATUS, cache.get("PLAY_STATUS"));
493 case MOVIE_MEDIA_TYPE:
494 connector.sendCommand(GET_MOVIE_MEDIA_TYPE, cache.get("MOVIE_MEDIA_TYPE"));
497 connector.sendCommand(GET_MOVIE_LOCATION, cache.get("MOVIE_LOCATION"));
500 case VIDEO_MODE_COMPOSITE:
501 case VIDEO_MODE_COMPONENT:
502 case VIDEO_MODE_HDMI:
503 connector.sendCommand(GET_VIDEO_MODE, cache.get("VIDEO_MODE"));
506 case VIDEO_COLOR_EOTF:
507 connector.sendCommand(GET_VIDEO_COLOR, cache.get("VIDEO_COLOR"));
510 case CONTENT_COLOR_EOTF:
511 connector.sendCommand(GET_CONTENT_COLOR, cache.get("CONTENT_COLOR"));
514 connector.sendCommand(GET_SCALE_MODE, cache.get("SCALE_MODE"));
518 connector.sendCommand(GET_SCREEN_MASK, cache.get("SCREEN_MASK"));
521 connector.sendCommand(GET_SCREEN_MASK2, cache.get("SCREEN_MASK2"));
523 case CINEMASCAPE_MASK:
524 connector.sendCommand(GET_CINEMASCAPE_MASK, cache.get("GET_CINEMASCAPE_MASK"));
526 case CINEMASCAPE_MODE:
527 connector.sendCommand(GET_CINEMASCAPE_MODE, cache.get("CINEMASCAPE_MODE"));
530 connector.sendCommand(GET_UI_STATE, cache.get("UI_STATE"));
532 case CHILD_MODE_STATE:
533 connector.sendCommand(GET_CHILD_MODE_STATE, cache.get("CHILD_MODE_STATE"));
535 case SYSTEM_READINESS_STATE:
536 connector.sendCommand(GET_SYSTEM_READINESS_STATE, cache.get("SYSTEM_READINESS_STATE"));
538 case HIGHLIGHTED_SELECTION:
539 connector.sendCommand(GET_HIGHLIGHTED_SELECTION, cache.get("HIGHLIGHTED_SELECTION"));
541 case USER_DEFINED_EVENT:
543 case USER_INPUT_PROMPT:
544 updateState(channel, StringType.EMPTY);
548 connector.sendCommand(GET_MUSIC_NOW_PLAYING_STATUS, cache.get("MUSIC_NOW_PLAYING_STATUS"));
553 case MUSIC_TRACK_HANDLE:
554 case MUSIC_ALBUM_HANDLE:
555 case MUSIC_NOWPLAY_HANDLE:
556 connector.sendCommand(GET_MUSIC_TITLE, cache.get("MUSIC_TITLE"));
558 case MUSIC_PLAY_MODE:
559 case MUSIC_PLAY_SPEED:
560 case MUSIC_TRACK_LENGTH:
561 case MUSIC_TRACK_POSITION:
562 case MUSIC_TRACK_PROGRESS:
563 connector.sendCommand(GET_MUSIC_PLAY_STATUS, cache.get("MUSIC_PLAY_STATUS"));
567 case DETAIL_ALBUM_TITLE:
568 case DETAIL_COVER_ART:
569 case DETAIL_COVER_URL:
570 case DETAIL_HIRES_COVER_URL:
573 case DETAIL_RUNNING_TIME:
576 case DETAIL_DIRECTORS:
578 case DETAIL_RATING_REASON:
579 case DETAIL_SYNOPSIS:
581 case DETAIL_COLOR_DESCRIPTION:
583 case DETAIL_ASPECT_RATIO:
584 case DETAIL_DISC_LOCATION:
585 updateState(channel, StringType.EMPTY);