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.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
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);
116 protected boolean isChannelLinked(String channel) {
117 return isLinked(channel);
121 public void initialize() {
122 final String uid = this.getThing().getUID().getAsString();
123 KaleidescapeThingConfiguration config = getConfigAs(KaleidescapeThingConfiguration.class);
125 this.thingTypeUID = thing.getThingTypeUID();
127 // Check configuration settings
128 String configError = null;
129 final String serialPort = config.serialPort;
130 final String host = config.host;
131 final Integer port = config.port;
132 final Integer updatePeriod = config.updatePeriod;
133 this.isLoadHighlightedDetails = config.loadHighlightedDetails;
134 this.isLoadAlbumDetails = config.loadAlbumDetails;
136 if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
137 configError = "undefined serialPort and host configuration settings; please set one of them";
138 } else if (host == null || host.isEmpty()) {
139 if (serialPort != null && serialPort.toLowerCase().startsWith("rfc2217")) {
140 configError = "use host and port configuration settings for a serial over IP connection";
144 configError = "undefined port configuration setting";
145 } else if (port <= 0) {
146 configError = "invalid port configuration setting";
150 if (configError != null) {
151 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
155 if (updatePeriod != null) {
156 this.updatePeriod = updatePeriod;
159 // check if volume is enabled
160 if (config.volumeEnabled) {
161 this.volumeEnabled = true;
162 this.volume = config.initialVolume;
163 this.updateState(VOLUME, new PercentType(this.volume));
164 this.updateState(MUTE, OnOffType.OFF);
167 if (serialPort != null) {
168 connector = new KaleidescapeSerialConnector(serialPortManager, serialPort, uid);
169 } else if (port != null) {
170 connector = new KaleidescapeIpConnector(host, port, uid);
172 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
173 "Either Serial port or Host & Port must be specifed");
177 updateStatus(ThingStatus.UNKNOWN);
179 scheduleReconnectJob();
180 schedulePollingJob();
184 public void dispose() {
185 cancelReconnectJob();
191 public Collection<Class<? extends ThingHandlerService>> getServices() {
192 return List.of(KaleidescapeThingActions.class);
195 public void handleRawCommand(@Nullable String command) {
196 synchronized (sequenceLock) {
198 connector.sendCommand(command);
199 } catch (KaleidescapeException e) {
200 logger.warn("K Command: {} failed", command);
206 public void handleCommand(ChannelUID channelUID, Command command) {
207 String channel = channelUID.getId();
209 if (getThing().getStatus() != ThingStatus.ONLINE) {
210 logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
213 synchronized (sequenceLock) {
214 if (!connector.isConnected()) {
215 logger.debug("Command {} from channel {} is ignored: connection not established", command, channel);
220 if (command instanceof RefreshType) {
221 handleRefresh(channel);
227 if (command instanceof OnOffType) {
228 connector.sendCommand(command == OnOffType.ON ? LEAVE_STANDBY : ENTER_STANDBY);
232 if (command instanceof PercentType percentCommand) {
233 this.volume = (int) percentCommand.doubleValue();
234 logger.debug("Got volume command {}", this.volume);
235 connector.sendCommand(SEND_EVENT_VOLUME_LEVEL_EQ + this.volume);
239 if (command instanceof OnOffType) {
240 this.isMuted = command == OnOffType.ON ? true : false;
242 connector.sendCommand(SEND_EVENT_MUTE + (this.isMuted ? MUTE_ON : MUTE_OFF));
245 if (command instanceof OnOffType) {
246 connector.sendCommand(command == OnOffType.ON ? MUSIC_REPEAT_ON : MUSIC_REPEAT_OFF);
250 if (command instanceof OnOffType) {
251 connector.sendCommand(command == OnOffType.ON ? MUSIC_RANDOM_ON : MUSIC_RANDOM_OFF);
256 handleControlCommand(command);
259 logger.debug("Command {} from channel {} failed: unexpected command", command, channel);
262 } catch (KaleidescapeException e) {
263 logger.debug("Command {} from channel {} failed: {}", command, channel, e.getMessage());
264 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
266 scheduleReconnectJob();
272 * Open the connection with the Kaleidescape component
274 * @return true if the connection is opened successfully or false if not
276 private synchronized boolean openConnection() {
277 connector.addEventListener(this);
280 } catch (KaleidescapeException e) {
281 logger.debug("openConnection() failed: {}", e.getMessage());
283 logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
284 return connector.isConnected();
288 * Close the connection with the Kaleidescape component
290 private synchronized void closeConnection() {
291 if (connector.isConnected()) {
293 connector.removeEventListener(this);
294 logger.debug("closeConnection(): disconnected");
299 public void onNewMessageEvent(KaleidescapeMessageEvent evt) {
300 lastEventReceived = System.currentTimeMillis();
302 // check if we are in standby
303 if (STANDBY_MSG.equals(evt.getKey())) {
304 if (!ThingStatusDetail.BRIDGE_OFFLINE.equals(thing.getStatusInfo().getStatusDetail())) {
305 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.BRIDGE_OFFLINE, STANDBY_MSG);
310 // Use the Enum valueOf to handle the message based on the event key. Otherwise there would be a huge
311 // case statement here
312 KaleidescapeMessageHandler.valueOf(evt.getKey()).handleMessage(evt.getValue(), this);
314 if (!evt.isCached()) {
315 cache.put(evt.getKey(), evt.getValue());
318 if (ThingStatusDetail.BRIDGE_OFFLINE.equals(thing.getStatusInfo().getStatusDetail())) {
319 // no longer in standby, update the status
320 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.friendlyName);
322 } catch (IllegalArgumentException e) {
323 logger.debug("Unhandled message: key {} = {}", evt.getKey(), evt.getValue());
328 * Schedule the reconnection job
330 private void scheduleReconnectJob() {
331 logger.debug("Schedule reconnect job");
332 cancelReconnectJob();
333 reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
334 synchronized (sequenceLock) {
335 if (!connector.isConnected()) {
336 logger.debug("Trying to reconnect...");
338 String error = EMPTY;
339 if (openConnection()) {
343 // register the connection in the Kaleidescape System log
344 connector.sendCommand(SEND_TO_SYSLOG + "openHAB Kaleidescape Binding version "
345 + org.openhab.core.OpenHAB.getVersion());
347 Set<String> initialCommands = new HashSet<>(Arrays.asList(GET_DEVICE_TYPE_NAME,
348 GET_FRIENDLY_NAME, GET_DEVICE_INFO, GET_SYSTEM_VERSION, GET_DEVICE_POWER_STATE,
349 GET_CINEMASCAPE_MASK, GET_CINEMASCAPE_MODE, GET_SCALE_MODE, GET_SCREEN_MASK,
350 GET_SCREEN_MASK2, GET_VIDEO_MODE, GET_UI_STATE, GET_HIGHLIGHTED_SELECTION,
351 GET_CHILD_MODE_STATE, GET_PLAY_STATUS, GET_MOVIE_LOCATION, GET_MOVIE_MEDIA_TYPE,
352 GET_PLAYING_TITLE_NAME));
354 // Premiere Players and Cinema One support music
355 if (thingTypeUID.equals(THING_TYPE_PLAYER) || thingTypeUID.equals(THING_TYPE_CINEMA_ONE)) {
356 initialCommands.addAll(Arrays.asList(GET_MUSIC_NOW_PLAYING_STATUS,
357 GET_MUSIC_PLAY_STATUS, GET_MUSIC_TITLE));
360 // everything after Premiere Player supports GET_SYSTEM_READINESS_STATE
361 if (!thingTypeUID.equals(THING_TYPE_PLAYER)) {
362 initialCommands.add(GET_SYSTEM_READINESS_STATE);
365 // only Strato supports the GET_*_COLOR commands
366 if (thingTypeUID.equals(THING_TYPE_STRATO)) {
367 initialCommands.addAll(Arrays.asList(GET_VIDEO_COLOR, GET_CONTENT_COLOR));
370 initialCommands.forEach(command -> {
372 connector.sendCommand(command);
373 } catch (KaleidescapeException e) {
374 logger.debug("{}: {}", "Error sending initial commands", e.getMessage());
378 if (this.updatePeriod == 1) {
379 connector.sendCommand(SET_STATUS_CUE_PERIOD_1);
381 } catch (KaleidescapeException e) {
382 error = "First command after connection failed";
383 logger.debug("{}: {}", error, e.getMessage());
387 error = "Reconnection failed";
389 if (!error.equals(EMPTY)) {
390 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error);
393 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.friendlyName);
394 lastEventReceived = System.currentTimeMillis();
397 }, 1, RECON_POLLING_INTERVAL_S, TimeUnit.SECONDS);
401 * Cancel the reconnection job
403 private void cancelReconnectJob() {
404 ScheduledFuture<?> reconnectJob = this.reconnectJob;
405 if (reconnectJob != null) {
406 reconnectJob.cancel(true);
407 this.reconnectJob = null;
412 * Schedule the polling job
414 private void schedulePollingJob() {
415 logger.debug("Schedule polling job");
418 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
419 synchronized (sequenceLock) {
420 if (connector.isConnected()) {
421 logger.debug("Polling the component for updated status...");
425 } catch (KaleidescapeException e) {
426 logger.debug("Polling error: {}", e.getMessage());
429 // if the last successful polling update was more than 1.25 intervals ago,
430 // the component is not responding even though the connection is still good
431 if ((System.currentTimeMillis() - lastEventReceived) > (POLLING_INTERVAL_S * 1.25 * 1000)) {
432 logger.debug("Component not responding to status requests");
433 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
434 "Component not responding to status requests");
436 scheduleReconnectJob();
440 }, POLLING_INTERVAL_S, POLLING_INTERVAL_S, TimeUnit.SECONDS);
444 * Cancel the polling job
446 private void cancelPollingJob() {
447 ScheduledFuture<?> pollingJob = this.pollingJob;
448 if (pollingJob != null) {
449 pollingJob.cancel(true);
450 this.pollingJob = null;
454 private void handleControlCommand(Command command) throws KaleidescapeException {
455 if (command instanceof PlayPauseType) {
456 if (command == PlayPauseType.PLAY) {
457 connector.sendCommand(PLAY);
458 } else if (command == PlayPauseType.PAUSE) {
459 connector.sendCommand(PAUSE);
461 } else if (command instanceof NextPreviousType) {
462 if (command == NextPreviousType.NEXT) {
463 connector.sendCommand(NEXT);
464 } else if (command == NextPreviousType.PREVIOUS) {
465 connector.sendCommand(PREVIOUS);
467 } else if (command instanceof RewindFastforwardType) {
468 if (command == RewindFastforwardType.FASTFORWARD) {
469 connector.sendCommand(SCAN_FORWARD);
470 } else if (command == RewindFastforwardType.REWIND) {
471 connector.sendCommand(SCAN_REVERSE);
474 logger.warn("Unknown control command: {}", command);
478 private void handleRefresh(String channel) throws KaleidescapeException {
481 connector.sendCommand(GET_DEVICE_POWER_STATE, cache.get("DEVICE_POWER_STATE"));
484 updateState(channel, new PercentType(this.volume));
487 updateState(channel, this.isMuted ? OnOffType.ON : OnOffType.OFF);
490 connector.sendCommand(GET_PLAYING_TITLE_NAME, cache.get("TITLE_NAME"));
500 connector.sendCommand(GET_PLAY_STATUS, cache.get("PLAY_STATUS"));
502 case MOVIE_MEDIA_TYPE:
503 connector.sendCommand(GET_MOVIE_MEDIA_TYPE, cache.get("MOVIE_MEDIA_TYPE"));
506 connector.sendCommand(GET_MOVIE_LOCATION, cache.get("MOVIE_LOCATION"));
509 case VIDEO_MODE_COMPOSITE:
510 case VIDEO_MODE_COMPONENT:
511 case VIDEO_MODE_HDMI:
512 connector.sendCommand(GET_VIDEO_MODE, cache.get("VIDEO_MODE"));
515 case VIDEO_COLOR_EOTF:
516 connector.sendCommand(GET_VIDEO_COLOR, cache.get("VIDEO_COLOR"));
519 case CONTENT_COLOR_EOTF:
520 connector.sendCommand(GET_CONTENT_COLOR, cache.get("CONTENT_COLOR"));
523 connector.sendCommand(GET_SCALE_MODE, cache.get("SCALE_MODE"));
527 connector.sendCommand(GET_SCREEN_MASK, cache.get("SCREEN_MASK"));
530 connector.sendCommand(GET_SCREEN_MASK2, cache.get("SCREEN_MASK2"));
532 case CINEMASCAPE_MASK:
533 connector.sendCommand(GET_CINEMASCAPE_MASK, cache.get("GET_CINEMASCAPE_MASK"));
535 case CINEMASCAPE_MODE:
536 connector.sendCommand(GET_CINEMASCAPE_MODE, cache.get("CINEMASCAPE_MODE"));
539 connector.sendCommand(GET_UI_STATE, cache.get("UI_STATE"));
541 case CHILD_MODE_STATE:
542 connector.sendCommand(GET_CHILD_MODE_STATE, cache.get("CHILD_MODE_STATE"));
544 case SYSTEM_READINESS_STATE:
545 connector.sendCommand(GET_SYSTEM_READINESS_STATE, cache.get("SYSTEM_READINESS_STATE"));
547 case HIGHLIGHTED_SELECTION:
548 connector.sendCommand(GET_HIGHLIGHTED_SELECTION, cache.get("HIGHLIGHTED_SELECTION"));
550 case USER_DEFINED_EVENT:
552 case USER_INPUT_PROMPT:
553 updateState(channel, StringType.EMPTY);
557 connector.sendCommand(GET_MUSIC_NOW_PLAYING_STATUS, cache.get("MUSIC_NOW_PLAYING_STATUS"));
562 case MUSIC_TRACK_HANDLE:
563 case MUSIC_ALBUM_HANDLE:
564 case MUSIC_NOWPLAY_HANDLE:
565 connector.sendCommand(GET_MUSIC_TITLE, cache.get("MUSIC_TITLE"));
567 case MUSIC_PLAY_MODE:
568 case MUSIC_PLAY_SPEED:
569 case MUSIC_TRACK_LENGTH:
570 case MUSIC_TRACK_POSITION:
571 case MUSIC_TRACK_PROGRESS:
572 connector.sendCommand(GET_MUSIC_PLAY_STATUS, cache.get("MUSIC_PLAY_STATUS"));
576 case DETAIL_ALBUM_TITLE:
577 case DETAIL_COVER_ART:
578 case DETAIL_COVER_URL:
579 case DETAIL_HIRES_COVER_URL:
582 case DETAIL_RUNNING_TIME:
585 case DETAIL_DIRECTORS:
587 case DETAIL_RATING_REASON:
588 case DETAIL_SYNOPSIS:
590 case DETAIL_COLOR_DESCRIPTION:
592 case DETAIL_ASPECT_RATIO:
593 case DETAIL_DISC_LOCATION:
594 updateState(channel, StringType.EMPTY);