2 * Copyright (c) 2010-2020 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.lgwebos.internal.handler;
15 import static org.openhab.binding.lgwebos.internal.LGWebOSBindingConstants.*;
17 import java.net.InetAddress;
18 import java.net.UnknownHostException;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.websocket.client.WebSocketClient;
30 import org.openhab.binding.lgwebos.action.LGWebOSActions;
31 import org.openhab.binding.lgwebos.internal.ChannelHandler;
32 import org.openhab.binding.lgwebos.internal.LGWebOSBindingConstants;
33 import org.openhab.binding.lgwebos.internal.LGWebOSStateDescriptionOptionProvider;
34 import org.openhab.binding.lgwebos.internal.LauncherApplication;
35 import org.openhab.binding.lgwebos.internal.MediaControlPlayer;
36 import org.openhab.binding.lgwebos.internal.MediaControlStop;
37 import org.openhab.binding.lgwebos.internal.PowerControlPower;
38 import org.openhab.binding.lgwebos.internal.RCButtonControl;
39 import org.openhab.binding.lgwebos.internal.TVControlChannel;
40 import org.openhab.binding.lgwebos.internal.ToastControlToast;
41 import org.openhab.binding.lgwebos.internal.VolumeControlMute;
42 import org.openhab.binding.lgwebos.internal.VolumeControlVolume;
43 import org.openhab.binding.lgwebos.internal.WakeOnLanUtility;
44 import org.openhab.binding.lgwebos.internal.handler.LGWebOSTVSocket.WebOSTVSocketListener;
45 import org.openhab.binding.lgwebos.internal.handler.core.AppInfo;
46 import org.openhab.binding.lgwebos.internal.handler.core.ResponseListener;
47 import org.openhab.core.config.core.Configuration;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.thing.ChannelUID;
50 import org.openhab.core.thing.Thing;
51 import org.openhab.core.thing.ThingStatus;
52 import org.openhab.core.thing.ThingStatusDetail;
53 import org.openhab.core.thing.binding.BaseThingHandler;
54 import org.openhab.core.thing.binding.ThingHandlerService;
55 import org.openhab.core.types.Command;
56 import org.openhab.core.types.State;
57 import org.openhab.core.types.StateOption;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * The {@link LGWebOSHandler} is responsible for handling commands, which are
63 * sent to one of the channels.
65 * @author Sebastian Prehn - initial contribution
68 public class LGWebOSHandler extends BaseThingHandler
69 implements LGWebOSTVSocket.ConfigProvider, WebOSTVSocketListener, PowerControlPower.ConfigProvider {
72 * constants for device polling
74 private static final int RECONNECT_INTERVAL_SECONDS = 10;
75 private static final int RECONNECT_START_UP_DELAY_SECONDS = 0;
76 private static final int CHANNEL_SUBSCRIPTION_DELAY_SECONDS = 1;
77 private static final String APP_ID_LIVETV = "com.webos.app.livetv";
82 private static final String MSG_MISSING_PARAM = "Missing parameter \"host\"";
84 private final Logger logger = LoggerFactory.getLogger(LGWebOSHandler.class);
86 // ChannelID to CommandHandler Map
87 private final Map<String, ChannelHandler> channelHandlers;
89 private final LauncherApplication appLauncher = new LauncherApplication();
91 private final WebSocketClient webSocketClient;
93 private final LGWebOSStateDescriptionOptionProvider stateDescriptionProvider;
95 private @Nullable LGWebOSTVSocket socket;
97 private @Nullable ScheduledFuture<?> reconnectJob;
98 private @Nullable ScheduledFuture<?> keepAliveJob;
99 private @Nullable ScheduledFuture<?> channelSubscriptionJob;
101 private @Nullable LGWebOSConfiguration config;
103 public LGWebOSHandler(Thing thing, WebSocketClient webSocketClient,
104 LGWebOSStateDescriptionOptionProvider stateDescriptionProvider) {
106 this.webSocketClient = webSocketClient;
107 this.stateDescriptionProvider = stateDescriptionProvider;
109 Map<String, ChannelHandler> handlers = new HashMap<>();
110 handlers.put(CHANNEL_VOLUME, new VolumeControlVolume());
111 handlers.put(CHANNEL_POWER, new PowerControlPower(this, scheduler));
112 handlers.put(CHANNEL_MUTE, new VolumeControlMute());
113 handlers.put(CHANNEL_CHANNEL, new TVControlChannel());
114 handlers.put(CHANNEL_APP_LAUNCHER, appLauncher);
115 handlers.put(CHANNEL_MEDIA_STOP, new MediaControlStop());
116 handlers.put(CHANNEL_TOAST, new ToastControlToast());
117 handlers.put(CHANNEL_MEDIA_PLAYER, new MediaControlPlayer());
118 handlers.put(CHANNEL_RCBUTTON, new RCButtonControl());
119 channelHandlers = Collections.unmodifiableMap(handlers);
122 private LGWebOSConfiguration getLGWebOSConfig() {
123 LGWebOSConfiguration c = config;
125 c = getConfigAs(LGWebOSConfiguration.class);
132 public void initialize() {
133 logger.debug("Initializing handler for thing {}", getThing().getUID());
134 LGWebOSConfiguration c = getLGWebOSConfig();
135 logger.trace("Handler initialized with config {}", c);
136 String host = c.getHost();
137 if (host.isEmpty()) {
138 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, MSG_MISSING_PARAM);
142 LGWebOSTVSocket s = new LGWebOSTVSocket(webSocketClient, this, host, c.getPort(), scheduler);
146 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "TV is off");
152 public void dispose() {
153 logger.debug("Disposing handler for thing {}", getThing().getUID());
156 stopChannelSubscriptionJob();
158 LGWebOSTVSocket s = socket;
164 config = null; // ensure config gets actually refreshed during re-initialization
168 private void startReconnectJob() {
169 ScheduledFuture<?> job = reconnectJob;
170 if (job == null || job.isCancelled()) {
171 reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
172 getSocket().disconnect();
173 getSocket().connect();
174 }, RECONNECT_START_UP_DELAY_SECONDS, RECONNECT_INTERVAL_SECONDS, TimeUnit.SECONDS);
178 private void stopReconnectJob() {
179 ScheduledFuture<?> job = reconnectJob;
180 if (job != null && !job.isCancelled()) {
187 * Keep alive ensures that the web socket connection is used and does not time out.
189 private void startKeepAliveJob() {
190 ScheduledFuture<?> job = keepAliveJob;
191 if (job == null || job.isCancelled()) {
192 // half of idle time out setting
193 long keepAliveInterval = this.webSocketClient.getMaxIdleTimeout() / 2;
195 // it is irrelevant which service is queried. Only need to send some packets over the wire
197 keepAliveJob = scheduler
198 .scheduleWithFixedDelay(() -> getSocket().getRunningApp(new ResponseListener<AppInfo>() {
201 public void onSuccess(AppInfo responseObject) {
202 // ignore - actual response is not relevant here
206 public void onError(String message) {
209 }), keepAliveInterval, keepAliveInterval, TimeUnit.MILLISECONDS);
214 private void stopKeepAliveJob() {
215 ScheduledFuture<?> job = keepAliveJob;
216 if (job != null && !job.isCancelled()) {
222 public LGWebOSTVSocket getSocket() {
223 LGWebOSTVSocket s = this.socket;
225 throw new IllegalStateException("Component called before it was initialized or already disposed.");
230 public LauncherApplication getLauncherApplication() {
235 public void handleCommand(ChannelUID channelUID, Command command) {
236 logger.debug("handleCommand({},{})", channelUID, command);
237 ChannelHandler handler = channelHandlers.get(channelUID.getId());
238 if (handler == null) {
240 "Unable to handle command {}. No handler found for channel {}. This must not happen. Please report as a bug.",
241 command, channelUID);
245 handler.onReceiveCommand(channelUID.getId(), this, command);
249 public String getMacAddress() {
250 return getLGWebOSConfig().getMacAddress();
254 public String getKey() {
255 return getLGWebOSConfig().getKey();
259 public void storeKey(@Nullable String key) {
260 if (!getKey().equals(key)) {
261 logger.debug("Store new access Key in the thing configuration");
262 // store it current configuration and avoiding complete re-initialization via handleConfigurationUpdate
263 getLGWebOSConfig().key = key;
265 // persist the configuration change
266 Configuration configuration = editConfiguration();
267 configuration.put(LGWebOSBindingConstants.CONFIG_KEY, key);
268 updateConfiguration(configuration);
273 public void storeProperties(Map<String, String> properties) {
274 logger.debug("storeProperties {}", properties);
275 Map<String, String> map = editProperties();
276 map.putAll(properties);
277 updateProperties(map);
281 public void onStateChanged(LGWebOSTVSocket.State state) {
284 postUpdate(CHANNEL_POWER, OnOffType.OFF);
287 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "TV is off");
288 channelHandlers.forEach((k, v) -> {
289 v.onDeviceRemoved(k, this);
290 v.removeAnySubscription(this);
300 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE,
301 "Registering - You may need to confirm pairing on TV.");
306 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, "Connected");
308 channelHandlers.forEach((k, v) -> {
309 // refresh subscriptions except on channel, which can only be subscribe in livetv app. see
311 if (!CHANNEL_CHANNEL.equals(k)) {
312 v.refreshSubscription(k, this);
314 v.onDeviceReady(k, this);
323 public void onError(String error) {
324 logger.debug("Connection failed - error: {}", error);
326 switch (getSocket().getState()) {
333 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection Failed: " + error);
338 public void setOptions(String channelId, List<StateOption> options) {
339 logger.debug("setOptions channelId={} options.size()={}", channelId, options.size());
340 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), channelId), options);
343 public void postUpdate(String channelId, State state) {
344 if (isLinked(channelId)) {
345 updateState(channelId, state);
348 // channel subscription only works when livetv app is started,
349 // therefore we need to slightly delay the subscription
350 if (CHANNEL_APP_LAUNCHER.equals(channelId)) {
351 if (APP_ID_LIVETV.equals(state.toString())) {
352 scheduleChannelSubscriptionJob();
354 stopChannelSubscriptionJob();
359 private void scheduleChannelSubscriptionJob() {
360 ScheduledFuture<?> job = channelSubscriptionJob;
361 if (job == null || job.isCancelled()) {
362 logger.debug("Schedule channel subscription job");
363 channelSubscriptionJob = scheduler.schedule(
364 () -> channelHandlers.get(CHANNEL_CHANNEL).refreshSubscription(CHANNEL_CHANNEL, this),
365 CHANNEL_SUBSCRIPTION_DELAY_SECONDS, TimeUnit.SECONDS);
369 private void stopChannelSubscriptionJob() {
370 ScheduledFuture<?> job = channelSubscriptionJob;
371 if (job != null && !job.isCancelled()) {
372 logger.debug("Stop channel subscription job");
375 channelSubscriptionJob = null;
379 public Collection<Class<? extends ThingHandlerService>> getServices() {
380 return Collections.singleton(LGWebOSActions.class);
384 * Make a best effort to automatically detect the MAC address of the TV.
385 * If this does not work automatically, users can still set it manually in the Thing config.
387 private void findMacAddress() {
388 LGWebOSConfiguration c = getLGWebOSConfig();
389 String host = c.getHost();
390 if (!host.isEmpty()) {
392 // validate host, so that no command can be injected
393 String macAddress = WakeOnLanUtility.getMACAddress(InetAddress.getByName(host).getHostAddress());
394 if (macAddress != null && !macAddress.equals(c.macAddress)) {
395 c.macAddress = macAddress;
396 // persist the configuration change
397 Configuration configuration = editConfiguration();
398 configuration.put(LGWebOSBindingConstants.CONFIG_MAC_ADDRESS, macAddress);
399 updateConfiguration(configuration);
401 } catch (UnknownHostException e) {
402 logger.debug("Unable to determine MAC address: {}", e.getMessage());
407 public List<String> reportApplications() {
408 return appLauncher.reportApplications(getThing().getUID());
411 public List<String> reportChannels() {
412 return ((TVControlChannel) channelHandlers.get(CHANNEL_CHANNEL)).reportChannels(getThing().getUID());