]> git.basschouten.com Git - openhab-addons.git/blob
576f37a0861390cc6caa7eb285d656b9c7adc0e9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.roku.internal.handler;
14
15 import static org.openhab.binding.roku.internal.RokuBindingConstants.*;
16
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpClient;
25 import org.openhab.binding.roku.internal.RokuConfiguration;
26 import org.openhab.binding.roku.internal.RokuHttpException;
27 import org.openhab.binding.roku.internal.RokuStateDescriptionOptionProvider;
28 import org.openhab.binding.roku.internal.communication.RokuCommunicator;
29 import org.openhab.binding.roku.internal.dto.Apps.App;
30 import org.openhab.binding.roku.internal.dto.DeviceInfo;
31 import org.openhab.binding.roku.internal.dto.Player;
32 import org.openhab.binding.roku.internal.dto.TvChannel;
33 import org.openhab.binding.roku.internal.dto.TvChannels.Channel;
34 import org.openhab.core.library.types.QuantityType;
35 import org.openhab.core.library.types.StringType;
36 import org.openhab.core.thing.ChannelUID;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingStatusDetail;
40 import org.openhab.core.thing.ThingTypeUID;
41 import org.openhab.core.thing.binding.BaseThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.openhab.core.types.StateOption;
45 import org.openhab.core.types.UnDefType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * The {@link RokuHandler} is responsible for handling commands, which are
51  * sent to one of the channels.
52  *
53  * @author Michael Lobstein - Initial contribution
54  */
55 @NonNullByDefault
56 public class RokuHandler extends BaseThingHandler {
57     private static final int DEFAULT_REFRESH_PERIOD_SEC = 10;
58
59     private final Logger logger = LoggerFactory.getLogger(RokuHandler.class);
60     private final HttpClient httpClient;
61     private final RokuStateDescriptionOptionProvider stateDescriptionProvider;
62
63     private @Nullable ScheduledFuture<?> refreshJob;
64     private @Nullable ScheduledFuture<?> appListJob;
65
66     private ThingTypeUID thingTypeUID = THING_TYPE_ROKU_PLAYER;
67     private RokuCommunicator communicator;
68     private DeviceInfo deviceInfo = new DeviceInfo();
69     private int refreshInterval = DEFAULT_REFRESH_PERIOD_SEC;
70     private boolean tvActive = false;
71
72     private Object sequenceLock = new Object();
73
74     public RokuHandler(Thing thing, HttpClient httpClient,
75             RokuStateDescriptionOptionProvider stateDescriptionProvider) {
76         super(thing);
77         this.httpClient = httpClient;
78         this.stateDescriptionProvider = stateDescriptionProvider;
79         this.communicator = new RokuCommunicator(httpClient, EMPTY, -1);
80     }
81
82     @Override
83     public void initialize() {
84         logger.debug("Initializing Roku handler");
85         RokuConfiguration config = getConfigAs(RokuConfiguration.class);
86         this.thingTypeUID = this.getThing().getThingTypeUID();
87
88         final @Nullable String host = config.hostName;
89
90         if (host != null && !EMPTY.equals(host)) {
91             this.communicator = new RokuCommunicator(httpClient, host, config.port);
92         } else {
93             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Host Name must be specified");
94             return;
95         }
96
97         if (config.refresh >= 10) {
98             refreshInterval = config.refresh;
99         }
100
101         updateStatus(ThingStatus.UNKNOWN);
102
103         try {
104             deviceInfo = communicator.getDeviceInfo();
105             thing.setProperty(PROPERTY_MODEL_NAME, deviceInfo.getModelName());
106             thing.setProperty(PROPERTY_MODEL_NUMBER, deviceInfo.getModelNumber());
107             thing.setProperty(PROPERTY_DEVICE_LOCAITON, deviceInfo.getUserDeviceLocation());
108             thing.setProperty(PROPERTY_SERIAL_NUMBER, deviceInfo.getSerialNumber());
109             thing.setProperty(PROPERTY_DEVICE_ID, deviceInfo.getDeviceId());
110             thing.setProperty(PROPERTY_SOFTWARE_VERSION, deviceInfo.getSoftwareVersion());
111             updateStatus(ThingStatus.ONLINE);
112         } catch (RokuHttpException e) {
113             logger.debug("Unable to retrieve Roku device-info. Exception: {}", e.getMessage(), e);
114         }
115         startAutomaticRefresh();
116         startAppListRefresh();
117     }
118
119     /**
120      * Start the job to periodically get status updates from the Roku
121      */
122     private void startAutomaticRefresh() {
123         ScheduledFuture<?> refreshJob = this.refreshJob;
124         if (refreshJob == null || refreshJob.isCancelled()) {
125             this.refreshJob = scheduler.scheduleWithFixedDelay(this::refreshPlayerState, 0, refreshInterval,
126                     TimeUnit.SECONDS);
127         }
128     }
129
130     /**
131      * Get a status update from the Roku and update the channels
132      */
133     private void refreshPlayerState() {
134         synchronized (sequenceLock) {
135             String activeAppId = ROKU_HOME_ID;
136             try {
137                 activeAppId = communicator.getActiveApp().getApp().getId();
138                 updateState(ACTIVE_APP, new StringType(activeAppId));
139                 if (TV_APP.equals(activeAppId)) {
140                     tvActive = true;
141                 } else {
142                     if (tvActive) {
143                         updateState(SIGNAL_MODE, UnDefType.UNDEF);
144                         updateState(SIGNAL_QUALITY, UnDefType.UNDEF);
145                         updateState(CHANNEL_NAME, UnDefType.UNDEF);
146                         updateState(PROGRAM_TITLE, UnDefType.UNDEF);
147                         updateState(PROGRAM_DESCRIPTION, UnDefType.UNDEF);
148                         updateState(PROGRAM_RATING, UnDefType.UNDEF);
149                     }
150                     tvActive = false;
151                 }
152                 updateStatus(ThingStatus.ONLINE);
153             } catch (RokuHttpException e) {
154                 logger.debug("Unable to retrieve Roku active-app info. Exception: {}", e.getMessage(), e);
155                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
156             }
157
158             // On the home app and when using the TV or TV inputs, do not update the play mode or time channels
159             if (!ROKU_HOME_ID.equals(activeAppId) && !activeAppId.contains(TV_INPUT)) {
160                 try {
161                     Player playerInfo = communicator.getPlayerInfo();
162                     // When nothing playing, 'close' is reported, replace with 'stop'
163                     updateState(PLAY_MODE, new StringType(playerInfo.getState().replaceAll(CLOSE, STOP)));
164
165                     // Remove non-numeric from string, ie: ' ms'
166                     String position = playerInfo.getPosition().replaceAll(NON_DIGIT_PATTERN, EMPTY);
167                     if (!EMPTY.equals(position)) {
168                         updateState(TIME_ELAPSED,
169                                 new QuantityType<>(Integer.parseInt(position) / 1000, API_SECONDS_UNIT));
170                     } else {
171                         updateState(TIME_ELAPSED, UnDefType.UNDEF);
172                     }
173
174                     String duration = playerInfo.getDuration().replaceAll(NON_DIGIT_PATTERN, EMPTY);
175                     if (!EMPTY.equals(duration)) {
176                         updateState(TIME_TOTAL,
177                                 new QuantityType<>(Integer.parseInt(duration) / 1000, API_SECONDS_UNIT));
178                     } else {
179                         updateState(TIME_TOTAL, UnDefType.UNDEF);
180                     }
181                 } catch (RokuHttpException e) {
182                     logger.debug("Unable to retrieve Roku media-player info. Exception: {}", e.getMessage(), e);
183                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
184                 }
185             } else {
186                 updateState(PLAY_MODE, UnDefType.UNDEF);
187                 updateState(TIME_ELAPSED, UnDefType.UNDEF);
188                 updateState(TIME_TOTAL, UnDefType.UNDEF);
189             }
190
191             if (thingTypeUID.equals(THING_TYPE_ROKU_TV) && tvActive) {
192                 try {
193                     TvChannel tvChannel = communicator.getActiveTvChannel();
194                     updateState(ACTIVE_CHANNEL, new StringType(tvChannel.getChannel().getNumber()));
195                     updateState(SIGNAL_MODE, new StringType(tvChannel.getChannel().getSignalMode()));
196                     updateState(SIGNAL_QUALITY,
197                             new QuantityType<>(tvChannel.getChannel().getSignalQuality(), API_PERCENT_UNIT));
198                     updateState(CHANNEL_NAME, new StringType(tvChannel.getChannel().getName()));
199                     updateState(PROGRAM_TITLE, new StringType(tvChannel.getChannel().getProgramTitle()));
200                     updateState(PROGRAM_DESCRIPTION, new StringType(tvChannel.getChannel().getProgramDescription()));
201                     updateState(PROGRAM_RATING, new StringType(tvChannel.getChannel().getProgramRatings()));
202                 } catch (RokuHttpException e) {
203                     logger.debug("Unable to retrieve Roku tv-active-channel info. Exception: {}", e.getMessage(), e);
204                 }
205             }
206         }
207     }
208
209     /**
210      * Start the job to periodically update list of apps installed on the the Roku
211      */
212     private void startAppListRefresh() {
213         ScheduledFuture<?> appListJob = this.appListJob;
214         if (appListJob == null || appListJob.isCancelled()) {
215             this.appListJob = scheduler.scheduleWithFixedDelay(this::refreshAppList, 10, 600, TimeUnit.SECONDS);
216         }
217     }
218
219     /**
220      * Update the dropdown that lists all apps installed on the Roku
221      */
222     private void refreshAppList() {
223         synchronized (sequenceLock) {
224             try {
225                 List<App> appList = communicator.getAppList();
226
227                 List<StateOption> appListOptions = new ArrayList<>();
228                 // Roku Home will be selected in the drop-down any time an app is not running.
229                 appListOptions.add(new StateOption(ROKU_HOME_ID, ROKU_HOME));
230
231                 appList.forEach(app -> {
232                     appListOptions.add(new StateOption(app.getId(), app.getValue()));
233                 });
234
235                 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), ACTIVE_APP),
236                         appListOptions);
237
238             } catch (RokuHttpException e) {
239                 logger.debug("Unable to retrieve Roku installed app-list. Exception: {}", e.getMessage(), e);
240             }
241
242             if (thingTypeUID.equals(THING_TYPE_ROKU_TV)) {
243                 try {
244                     List<Channel> channelsList = communicator.getTvChannelList();
245
246                     List<StateOption> channelListOptions = new ArrayList<>();
247                     channelsList.forEach(channel -> {
248                         if (!channel.isUserHidden()) {
249                             channelListOptions.add(new StateOption(channel.getNumber(),
250                                     channel.getNumber() + " - " + channel.getName()));
251                         }
252                     });
253
254                     stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), ACTIVE_CHANNEL),
255                             channelListOptions);
256
257                 } catch (RokuHttpException e) {
258                     logger.debug("Unable to retrieve Roku tv-channels. Exception: {}", e.getMessage(), e);
259                 }
260             }
261         }
262     }
263
264     @Override
265     public void dispose() {
266         ScheduledFuture<?> refreshJob = this.refreshJob;
267         if (refreshJob != null) {
268             refreshJob.cancel(true);
269             this.refreshJob = null;
270         }
271
272         ScheduledFuture<?> appListJob = this.appListJob;
273         if (appListJob != null) {
274             appListJob.cancel(true);
275             this.appListJob = null;
276         }
277     }
278
279     @Override
280     public void handleCommand(ChannelUID channelUID, Command command) {
281         if (command instanceof RefreshType) {
282             logger.debug("Unsupported refresh command: {}", command);
283         } else if (channelUID.getId().equals(BUTTON)) {
284             synchronized (sequenceLock) {
285                 try {
286                     communicator.keyPress(command.toString());
287                 } catch (RokuHttpException e) {
288                     logger.debug("Unable to send keypress to Roku, key: {}, Exception: {}", command, e.getMessage());
289                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
290                 }
291             }
292         } else if (channelUID.getId().equals(ACTIVE_APP)) {
293             synchronized (sequenceLock) {
294                 try {
295                     String appId = command.toString();
296                     // Roku Home(-1) is not a real appId, just press the home button instead
297                     if (!ROKU_HOME_ID.equals(appId)) {
298                         communicator.launchApp(appId);
299                     } else {
300                         communicator.keyPress(ROKU_HOME_BUTTON);
301                     }
302                 } catch (RokuHttpException e) {
303                     logger.debug("Unable to launch app on Roku, appId: {}, Exception: {}", command, e.getMessage());
304                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
305                 }
306             }
307         } else if (channelUID.getId().equals(ACTIVE_CHANNEL)) {
308             synchronized (sequenceLock) {
309                 try {
310                     communicator.launchTvChannel(command.toString());
311                 } catch (RokuHttpException e) {
312                     logger.debug("Unable to change channel on Roku TV, channelNumber: {}, Exception: {}", command,
313                             e.getMessage());
314                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
315                 }
316             }
317         } else {
318             logger.debug("Unsupported command: {}", command);
319         }
320     }
321 }